/* profile-screens.jsx — ProfileHome + PostDetail. Exports to window. */

/* ============================================================
   PROFILE HOME
   ============================================================ */
function ProfileHome({ me, brews, onOpenBrew, onSettings, onEdit, onCompose }) {
  const [tab, setTab] = React.useState('brews');
  const teas = brews.filter((b) => b.kind === 'tea');
  const takes = brews.filter((b) => b.kind === 'take');
  const shown = tab === 'brews' ? brews : tab === 'teas' ? teas : takes;
  // split into 2 columns for a sticky-board masonry feel
  const cols = [[], []];
  shown.forEach((b, i) => cols[i % 2].push(b));

  return (
    <div style={{ position: 'relative', height: '100%' }}>
    <Screen
      headerLeft={<Wordmark size={20} />}
      headerRight={<IconBtn label="Settings" onClick={onSettings}><IconGear size={24} /></IconBtn>}
    >
      {/* hero */}
      <div style={{ display: 'flex', gap: 16, alignItems: 'flex-start', marginTop: 4 }}>
        <div style={{ position: 'relative', flex: '0 0 auto' }}>
          <span style={{ position: 'absolute', top: -11, left: '50%', transform: 'translateX(-50%) rotate(-5deg)', zIndex: 3 }}>
            <Tape label="that's me" rotate={-5} />
          </span>
          <div style={{ width: 104, height: 104, ...wobbly.blob, ...tilt(-3), border: '3px solid var(--ink)', boxShadow: 'var(--sh-hard)', overflow: 'hidden', background: 'var(--muted)' }}>
            <img src={me.avatar} alt={me.name} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
          </div>
        </div>
        <div style={{ flex: 1, minWidth: 0, paddingTop: 6 }}>
          <h1 className="font-head" style={{ fontWeight: 700, fontSize: 28, margin: 0, lineHeight: 1.05 }}>{me.name}</h1>
          <div className="font-body" style={{ color: 'var(--secondary)', fontSize: 17, marginTop: 1 }}>{me.handle}</div>
          {me.verifiedPseudonym && (
            <div style={{ marginTop: 7 }}><Badge tone="secondary">🔒 verified pseudonym</Badge></div>
          )}
        </div>
      </div>

      <p className="font-body" style={{ fontSize: 17, lineHeight: 1.4, margin: '14px 2px 0', color: 'var(--ink)' }}>{me.bio}</p>
      <div className="font-body" style={{ fontSize: 15, color: 'var(--ink-muted)', margin: '8px 2px 0' }}>☕ brewing since {me.joined}</div>

      {/* stats */}
      <div style={{ display: 'flex', gap: 10, margin: '18px 0 0' }}>
        <div className="stat" style={tilt(-1.5)}><div className="stat__n">{fmtN(me.stats.brews)}</div><div className="stat__l">Brews</div></div>
        <div className="stat" style={tilt(1)}><div className="stat__n">{fmtN(me.stats.paps)}</div><div className="stat__l">Paps</div></div>
        <div className="stat" style={tilt(-1)}><div className="stat__n">{fmtN(me.stats.stakeout)}</div><div className="stat__l">Stakeout</div></div>
      </div>

      {/* actions */}
      <div style={{ display: 'flex', gap: 10, margin: '14px 0 2px' }}>
        <Button variant="accent" block onClick={onEdit} style={{ minHeight: 48, fontSize: 18 }}>
          <IconPencil size={19} /> Edit profile
        </Button>
        <Button block style={{ minHeight: 48, fontSize: 18, flex: '0 0 auto', width: 64, padding: 0 }} aria-label="Share profile">
          <IconShare size={20} />
        </Button>
      </div>

      {/* tabs */}
      <div className="seg" style={{ margin: '20px 0 14px' }}>
        {[['brews', 'All', <IconGrid size={17} key="g" />], ['teas', `Teas`, '🫖'], ['takes', `Takes`, '✦']].map(([id, lbl, ic]) => (
          <button key={id} className={`seg__btn ${tab === id ? 'seg__btn--on' : ''}`} style={tilt(tab === id ? -1 : 0)} onClick={() => setTab(id)}>
            <span style={{ fontSize: 16 }}>{ic}</span>{lbl}
          </button>
        ))}
      </div>

      {/* brew grid */}
      {shown.length > 0 ? (
        <div style={{ display: 'flex', gap: 11, alignItems: 'flex-start' }}>
          {cols.map((col, ci) => (
            <div key={ci} style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', gap: 11 }}>
              {col.map((b, i) => <BrewCard key={b.id} brew={b} rot={((ci + i) % 2 ? 1 : -1) * 1.2} onClick={() => onOpenBrew(b.id)} />)}
            </div>
          ))}
        </div>
      ) : (
        <EmptyState emoji="🫖"
          title={tab === 'teas' ? 'no Teas yet' : tab === 'takes' ? 'no Takes yet' : 'no Brews yet'}
          body={tab === 'takes' ? "Reply to a Wire story with your hot Take and it'll show up here."
            : "You haven't spilled anything yet. Tap Spill a Tea and say something — the Kettle's listening."}
          action={tab === 'takes' ? null : 'Spill a Tea'} onAction={onCompose} />
      )}
      <div style={{ height: 8 }} />
    </Screen>
    {onCompose && (
      <button className="fab" onClick={onCompose} aria-label="Spill a Tea">
        <svg width="28" height="28" viewBox="0 0 28 28" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round"><path d="M14 6v16M6 14h16" /></svg>
      </button>
    )}
    </div>
  );
}

function BrewCard({ brew, rot, onClick }) {
  const isTea = brew.kind === 'tea';
  return (
    <button className={`gcard ${isTea ? 'gcard--tea' : ''}`} style={tilt(rot)} onClick={onClick}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 6 }}>
        <Badge tone={isTea ? 'ink' : 'secondary'}>{isTea ? '🫖 Tea' : '✦ Take'}</Badge>
        <span className="font-body" style={{ fontSize: 14, opacity: .6 }}>{brew.time}</span>
      </div>
      {brew.wire && <div className="font-body" style={{ fontSize: 13.5, color: 'var(--secondary)', opacity: .9, marginTop: -2 }}>↳ {brew.wire}</div>}
      {brew.image && <div className="gcard__img" style={tilt(-0.6)}><img src={brew.image} alt="" /></div>}
      <div className="gcard__body">{brew.body.length > 120 ? brew.body.slice(0, 118) + '…' : brew.body}</div>
      <div className="gcard__meta">
        <span className="rs"><IconSip size={16} />{fmtN(brew.sips)}</span>
        <span className="rs"><IconTake size={16} />{fmtN(brew.takes.length)}</span>
        <span className="rs"><IconSplash size={16} />{fmtN(brew.splash)}</span>
      </div>
    </button>
  );
}

/* ============================================================
   POST (BREW) DETAIL
   ============================================================ */
function PostDetail({ brew, me, onBack, replyImage }) {
  const [sipped, setSipped] = React.useState(false);
  const [splashed, setSplashed] = React.useState(false);
  const isTea = brew.kind === 'tea';
  const sips = brew.sips + (sipped ? 1 : 0);
  const splash = brew.splash + (splashed ? 1 : 0);

  return (
    <Screen title="Brew" onBack={onBack}
      headerRight={<IconBtn label="Share" tiltDeg={3}><IconShare size={20} /></IconBtn>}
      footer={<TakeComposer me={me} initialImage={replyImage} />}>
      {/* author */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <div style={{ width: 50, height: 50, ...wobbly.blob, ...tilt(-3), border: '2px solid var(--ink)', overflow: 'hidden', flex: '0 0 auto', boxShadow: 'var(--sh-soft)' }}>
          <img src={me.avatar} alt={me.name} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="font-head" style={{ fontWeight: 700, fontSize: 19 }}>{me.name}</div>
          <div className="font-body" style={{ color: 'var(--secondary)', fontSize: 15 }}>{me.handle} · {brew.time}</div>
        </div>
        <Badge tone={isTea ? 'ink' : 'secondary'}>{isTea ? '🫖 Tea' : '✦ Take'}</Badge>
      </div>

      {/* unverified / wire banner */}
      <div className="postit" style={{ ...wobbly.sm, ...tilt(isTea ? 1 : -1), padding: '9px 13px', margin: '14px 0 0', display: 'flex', gap: 8, alignItems: 'center', background: isTea ? 'var(--postit)' : 'var(--surface)', border: '2px solid var(--ink)' }}>
        <span style={{ fontSize: 17 }}>{isTea ? '👀' : '🔗'}</span>
        <span className="font-body" style={{ fontSize: 15, color: isTea ? 'var(--postit-ink)' : 'var(--ink)' }}>
          {isTea ? 'From the Kettle — unverified. Read for fun, not facts.' : <>Linked to The Wire — <b>{brew.wire}</b>. Tap to read the source.</>}
        </span>
      </div>

      {/* body */}
      <p className="font-body" style={{ fontSize: 22, lineHeight: 1.42, margin: '16px 2px 0' }}>{brew.body}</p>

      {/* attached image */}
      {brew.image && (
        <div style={{ position: 'relative', margin: '22px 6px 2px', ...tilt(isTea ? -1 : 1) }}>
          <span style={{ position: 'absolute', top: -13, left: '50%', transform: 'translateX(-50%) rotate(-3deg)', zIndex: 3 }}>
            <Tape label={isTea ? '📷 my photo' : '📰 from the article'} rotate={-3} />
          </span>
          <div className="pimg">
            <img src={brew.image} alt={isTea ? 'Photo attached to this Tea' : 'Article image from The Wire'} />
            {!isTea && brew.wireUrl && <div className="pimg__cap">🔗 {brew.wireUrl}</div>}
          </div>
        </div>
      )}

      {/* reaction bar */}
      <div className="rbar" style={{ flexWrap: 'wrap', gap: 9, margin: '18px 0 2px' }}>
        <ReactionPill icon={<IconSip size={19} />} n={sips} on={sipped} onClick={() => setSipped((s) => !s)} />
        <ReactionPill icon={<IconSplash size={19} />} n={splash} on={splashed} onClick={() => setSplashed((s) => !s)} />
        <ReactionPill icon={<IconTake size={19} />} n={brew.takes.length} />
        <ReactionPill icon={<IconWhisper size={19} />} n={brew.whispers} />
      </div>

      <div style={{ margin: '20px 0 6px', display: 'flex', alignItems: 'center', gap: 10 }}>
        <span className="font-head" style={{ fontWeight: 700, fontSize: 20 }}>Takes</span>
        <span className="font-body" style={{ color: 'var(--ink-muted)', fontSize: 16 }}>{brew.takes.length}</span>
        <span style={{ flex: 1 }}><WavyDivider /></span>
      </div>

      {/* comments */}
      <div>
        {brew.takes.map((t, i) => (
          <div className="take" key={i}>
            <span className="take__av" style={tilt((i % 2 ? 1 : -1) * 2)}><img src={t.av} alt="" /></span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, flexWrap: 'wrap' }}>
                <span className="font-body" style={{ color: 'var(--secondary)', fontSize: 16 }}>{t.by}</span>
                <span className="font-body" style={{ color: 'var(--ink-muted)', fontSize: 14 }}>{t.t}</span>
              </div>
              <p className="font-body" style={{ fontSize: 17, lineHeight: 1.35, margin: '2px 0 6px' }}>{t.text}</p>
              {t.image && <div className="take__img" style={tilt(-1.2)}><img src={t.image} alt="Photo in this Take" /></div>}
              <button className="font-body" style={{ display: 'inline-flex', alignItems: 'center', gap: 5, background: 'none', border: 'none', cursor: 'pointer', color: 'var(--ink-muted)', fontSize: 15, padding: 0 }}>
                <IconSip size={15} /> {fmtN(t.sips)}
              </button>
            </div>
          </div>
        ))}
      </div>
      <div style={{ height: 6 }} />
    </Screen>
  );
}

Object.assign(window, { ProfileHome, BrewCard, PostDetail, TakeComposer });

/* ============================================================
   Reply composer (add a Take) — text + optional photo
   ============================================================ */
function TakeComposer({ me, initialImage = null }) {
  const [text, setText] = React.useState('');
  const [img, setImg] = React.useState(initialImage);
  const fileRef = React.useRef(null);
  const pick = (e) => { const f = e.target.files && e.target.files[0]; if (f) setImg(URL.createObjectURL(f)); };
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
      {img && (
        <div className="preview" style={{ ...tilt(-1.2), alignSelf: 'flex-start', maxWidth: 150 }}>
          <img src={img} alt="Your Take's photo" style={{ maxHeight: 110 }} />
          <button className="preview__x" onClick={() => setImg(null)} aria-label="Remove photo" style={{ width: 30, height: 30 }}>
            <IconX size={16} />
          </button>
        </div>
      )}
      <div className="card" style={{ ...wobbly.pill, display: 'flex', alignItems: 'center', gap: 8, padding: '6px 6px 6px 15px', boxShadow: 'var(--sh-soft)' }}>
        <input className="font-body" value={text} onChange={(e) => setText(e.target.value)} placeholder="add your Take…"
          style={{ flex: 1, border: 'none', outline: 'none', background: 'transparent', color: 'var(--ink)', fontSize: 17, minWidth: 0, fontFamily: "'Patrick Hand', cursive" }} />
        <input ref={fileRef} type="file" accept="image/*" onChange={pick} style={{ display: 'none' }} />
        <button className="attach" onClick={() => fileRef.current && fileRef.current.click()} aria-label="Add photo" style={{ width: 42, height: 42 }}>
          <IconCamera size={20} />
        </button>
        <Button variant="accent" disabled={!text.trim() && !img} style={{ minHeight: 42, fontSize: 17, padding: '6px 16px' }}>Post</Button>
      </div>
    </div>
  );
}
