/* screen-creator-application-detail.jsx — Application detail, morphs by status
   ─────────────────────────────────────────────────────────────────────────────
   Status = pending | shortlisted | accepted | rejected
   Click row in My Applications → window.__appStatus is set, then route here.
   A status switcher at top lets the user scrub through all 4 states for demo.
*/
/* global React, AppSidebar, AppTopbar, useRouter, useT, Avatar, Pill, Icon, Counter */

const APP_PROFILES = {
  pending: {
    brand: 'DermaQ', cat: 'Skincare brand', title: 'Acne care · awareness video', logo: 'D',
    rate: 1800, applied: '12m ago', gradient: 'linear-gradient(135deg, #79FEE7 0%, #009CFF 110%)',
    platform: 'TikTok', platformIcon: Icon.tiktok, band: '$1.2K – $2.4K', deadline: 'May 22', appliedCount: 18,
  },
  shortlisted: {
    brand: 'Highland Coffee', cat: 'F&B', title: 'New espresso flight', logo: 'H',
    rate: 1400, applied: '4d ago', gradient: 'linear-gradient(135deg, #FFC3D6 0%, #FF7A59 110%)',
    platform: 'IG reels', platformIcon: Icon.instagram, band: '$1.0K – $2.0K', skus: 3,
  },
  accepted: {
    brand: 'YODY', cat: 'Fashion brand', title: 'Tet 2026 fashion drop', logo: 'Y',
    rate: 2200, applied: '2d ago', gradient: 'linear-gradient(135deg, #FFC3D6 0%, #FF6FA3 110%)',
    platform: 'IG reels', platformIcon: Icon.instagram, paid: 540, project: 'Jun 04 – Jul 02',
  },
  rejected: {
    brand: 'Saigon Vegan', cat: 'F&B', title: 'Vegan snack hero spot', logo: 'S',
    rate: 1200, applied: '1w ago', gradient: 'linear-gradient(135deg, #79FEE7 0%, #1FD6B4 110%)',
    platform: 'TikTok', platformIcon: Icon.tiktok, band: '$0.8K – $1.6K', closedDays: 5,
  },
};

const SIMILAR_BRIEFS = [
  { logo: 'H', color: 'var(--coral)', title: 'New espresso flight', sub: 'Highland Coffee · $1.0K – $2.0K · 7d', match: 88 },
  { logo: 'L', color: 'var(--lavender-deep)', title: 'Spring tone-up gel launch', sub: 'Laneige VN · $1.4K – $2.6K · 4d', match: 85 },
  { logo: 'S', color: 'var(--mint-deep)', title: 'Vegan snack hero spot', sub: 'Saigon Vegan · $0.8K – $1.6K · 9d', match: 78 },
];

// ── Shared bits ────────────────────────────────────────────────────
function Stepper({ steps }) {
  return (
    <div className="row items-center" style={{ padding: '16px 20px', background: 'white', borderRadius: 14, border: '1px solid var(--line)', marginBottom: 16 }}>
      {steps.map((s, i, arr) => {
        const stateBg = s.state === 'done' ? 'var(--mint-deep)' : s.state === 'now' ? 'var(--ink)' : s.state === 'fail' ? 'var(--pink-hot)' : 'var(--bg-soft)';
        const stateFg = s.state === 'todo' ? 'var(--ink-soft)' : 'white';
        return (
          <React.Fragment key={i}>
            <div className="row items-center gap-10" style={{ flex: 'none' }}>
              <div style={{
                width: 28, height: 28, borderRadius: 999, background: stateBg, color: stateFg,
                display: 'grid', placeItems: 'center', fontWeight: 800, fontSize: 12,
                boxShadow: s.state === 'now' ? '0 0 0 4px rgba(0,43,80,0.08)' : 'none'
              }}>{s.state === 'done' ? '✓' : s.state === 'fail' ? '✕' : i + 1}</div>
              <div>
                <div className="bold" style={{ fontSize: 12.5, color: s.state === 'todo' ? 'var(--ink-soft)' : 'var(--ink)' }}>{s.label}</div>
                <div className="muted" style={{ fontSize: 10.5 }}>{s.when}</div>
              </div>
            </div>
            {i < arr.length - 1 && (
              <div style={{
                flex: 1, height: 2, margin: '0 12px',
                background: s.state === 'done' ? 'var(--mint-deep)' : 'var(--line)'
              }} />
            )}
          </React.Fragment>
        );
      })}
    </div>
  );
}

function Hero({ p, badge, rightLabel = 'Your rate', rightValue, rightSub }) {
  return (
    <div style={{
      padding: 28, borderRadius: 18, background: p.gradient, color: 'var(--ink)',
      position: 'relative', overflow: 'hidden', marginBottom: 16
    }}>
      <div style={{ position: 'absolute', top: -50, right: -50, width: 220, height: 220, borderRadius: '50%', background: 'rgba(255,255,255,0.4)', filter: 'blur(20px)' }} />
      <div className="row items-start gap-20" style={{ position: 'relative', zIndex: 1 }}>
        <div style={{
          width: 72, height: 72, borderRadius: 16, background: 'white',
          display: 'grid', placeItems: 'center', fontFamily: 'Space Grotesk',
          fontWeight: 800, fontSize: 28, color: 'var(--ink)',
          boxShadow: '0 8px 20px rgba(0,43,80,0.18)', flexShrink: 0
        }}>{p.logo}</div>
        <div className="flex-1" style={{ minWidth: 0 }}>
          <Pill variant="dark">{p.brand} · {p.cat}</Pill>
          <h2 className="font-display" style={{ fontSize: 28, fontWeight: 700, margin: '6px 0 0', letterSpacing: '-0.02em' }}>{p.title}</h2>
          <div className="row gap-6 mt-3" style={{ flexWrap: 'wrap' }}>
            <Pill variant="dark" icon={p.platformIcon}>{p.platform}</Pill>
            {p.band && <Pill variant="dark">Brand band {p.band}</Pill>}
            {p.deadline && <Pill variant="dark">Deadline {p.deadline}</Pill>}
            {p.appliedCount && <Pill variant="dark">{p.appliedCount} applied</Pill>}
            {p.skus && <Pill variant="dark">{p.skus} SKUs</Pill>}
            {p.project && <Pill variant="dark">Project · {p.project}</Pill>}
            {badge && badge}
          </div>
        </div>
        <div className="text-right" style={{ flexShrink: 0 }}>
          <div className="cap-label" style={{ color: 'var(--ink)', opacity: 0.6 }}>{rightLabel}</div>
          <div className="font-display tabular" style={{ fontSize: 36, fontWeight: 700, letterSpacing: '-0.025em', lineHeight: 1, marginTop: 4 }}>{rightValue}</div>
          {rightSub && <div className="muted" style={{ fontSize: 11, marginTop: 4, color: 'var(--ink)', opacity: 0.65 }}>{rightSub}</div>}
        </div>
      </div>
    </div>
  );
}

function Banner({ kind, icon, title, body, actions }) {
  const palettes = {
    pending:     { bg: 'linear-gradient(135deg, rgba(254,233,96,0.30), rgba(255,206,92,0.22))', border: 'rgba(242,196,17,0.4)', iconBg: '#F2C411' },
    shortlisted: { bg: 'linear-gradient(135deg, rgba(0,156,255,0.10), rgba(121,254,231,0.10))', border: 'rgba(0,156,255,0.3)', iconBg: 'var(--cyan)' },
    accepted:    { bg: 'linear-gradient(135deg, rgba(31,214,180,0.18), rgba(121,254,231,0.18))', border: 'rgba(31,214,180,0.4)', iconBg: 'var(--mint-deep)' },
    rejected:    { bg: 'linear-gradient(135deg, rgba(255,111,163,0.12), rgba(255,195,214,0.12))', border: 'rgba(255,111,163,0.35)', iconBg: 'var(--pink-hot)' },
  };
  const p = palettes[kind];
  return (
    <div className="row items-center gap-16" style={{
      padding: 18, borderRadius: 14, background: p.bg, border: '1px solid ' + p.border, marginBottom: 16
    }}>
      <div style={{
        width: 44, height: 44, borderRadius: 12, background: p.iconBg, color: 'white',
        display: 'grid', placeItems: 'center', flexShrink: 0, fontSize: 22
      }}>{icon}</div>
      <div className="flex-1" style={{ minWidth: 0 }}>
        <div className="bold" style={{ fontSize: 14 }}>{title}</div>
        <div className="muted" style={{ fontSize: 12, marginTop: 2, lineHeight: 1.5 }}>{body}</div>
      </div>
      <div className="row gap-8" style={{ flexShrink: 0 }}>{actions}</div>
    </div>
  );
}

function ActivityTimeline({ items }) {
  return (
    <div style={{ position: 'relative' }}>
      <div style={{ position: 'absolute', left: 11, top: 6, bottom: 6, width: 2, background: 'var(--bg-soft)' }} />
      {items.map((it, i) => (
        <div key={i} className="row items-start gap-12" style={{ position: 'relative', padding: '10px 0' }}>
          <div style={{
            width: 24, height: 24, borderRadius: 999, flexShrink: 0, zIndex: 1,
            background: it.color || 'var(--bg-soft)',
            color: it.color === 'var(--bg-soft)' || !it.color ? 'var(--ink-soft)' : 'white',
            border: '3px solid white',
            display: 'grid', placeItems: 'center', fontWeight: 800, fontSize: 11
          }}>{it.icon || ''}</div>
          <div className="flex-1" style={{ paddingTop: 2 }}>
            <div className="muted" style={{ fontSize: 10.5, fontWeight: 600 }}>{it.when}</div>
            <div className="bold" style={{ fontSize: 12.5, marginTop: 1, color: it.faded ? 'var(--ink-soft)' : 'var(--ink)' }}>{it.what}</div>
            {it.who && <div className="muted" style={{ fontSize: 11, marginTop: 2 }}>{it.who}</div>}
          </div>
        </div>
      ))}
    </div>
  );
}

function BrandSnapshot({ p }) {
  return (
    <div className="card-elevated" style={{ marginBottom: 14 }}>
      <div className="title-md mb-3">The brief</div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px 16px', fontSize: 12.5 }}>
        <div><div className="cap-label" style={{ fontSize: 9 }}>Goal</div><div className="bold mt-1">{p.brand === 'DermaQ' ? 'Awareness for acne-care launch' : p.brand === 'Highland Coffee' ? 'New SKU launch · trial drive' : p.brand === 'YODY' ? 'Tet drop · cultural fashion moment' : 'Hero brand spot for vegan line'}</div></div>
        <div><div className="cap-label" style={{ fontSize: 9 }}>Audience</div><div className="bold mt-1">HCM/HN · 18–24F</div></div>
        <div><div className="cap-label" style={{ fontSize: 9 }}>Timeline</div><div className="bold mt-1">{p.brand === 'YODY' ? 'Jun 04 – Jul 02' : 'May 14 – Jun 11'}</div></div>
        <div><div className="cap-label" style={{ fontSize: 9 }}>Deliverables</div><div className="bold mt-1">{p.brand === 'Highland Coffee' ? '3 reels · 1 carousel' : p.brand === 'YODY' ? '3 reels + analytics' : '1 TikTok + 1 follow-up'}</div></div>
      </div>
      <div className="row gap-6 mt-4" style={{ flexWrap: 'wrap' }}>
        <Pill variant="lav">Honest before/after</Pill>
        <Pill variant="lav">No filter heavy</Pill>
        <Pill variant="lav">#{p.brand.replace(/\s/g, '')}</Pill>
      </div>
      <a className="row items-center gap-6 mt-4 bold" style={{ fontSize: 12, color: 'var(--cyan-dark)', cursor: 'pointer' }}>View full brief {Icon.arrow}</a>
    </div>
  );
}

function AIFitCard({ fit = 92 }) {
  const bars = [
    ['Audience overlap · HCM 18–24F', 96, 'var(--mint-deep)'],
    ['Category match', 94, 'var(--cyan)'],
    ['ER vs target threshold', 88, 'var(--indigo)'],
    ['Past performance · same vertical', 92, 'var(--pink-hot)'],
  ];
  return (
    <div className="card-elevated" style={{ marginBottom: 14 }}>
      <div className="row items-center justify-between mb-1">
        <div className="title-md">Why you're a {fit}% match</div>
        <Pill variant="mint">AI</Pill>
      </div>
      <div className="muted mb-3" style={{ fontSize: 11.5 }}>Breakdown locked at submission</div>
      {bars.map(([l, v, c], i) => (
        <div key={i} style={{ marginBottom: 10 }}>
          <div className="row items-center justify-between" style={{ fontSize: 12, fontWeight: 600 }}>
            <span>{l}</span>
            <span className="tabular bold">{v}%</span>
          </div>
          <div style={{ height: 6, borderRadius: 999, background: 'var(--bg-soft)', overflow: 'hidden', marginTop: 4 }}>
            <div style={{ height: '100%', width: v + '%', background: c, borderRadius: 999, animation: `grow-w .9s ${i * 0.08}s cubic-bezier(.4,0,.2,1) both`, transformOrigin: 'left' }} />
          </div>
        </div>
      ))}
    </div>
  );
}

function SimilarBriefs({ go, title = 'While you wait', sub = '3 briefs that also match your profile' }) {
  return (
    <div className="card-elevated">
      <div className="title-md mb-1">{title}</div>
      <div className="muted mb-3" style={{ fontSize: 12 }}>{sub}</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {SIMILAR_BRIEFS.map((b, i) => (
          <div key={i} className="row items-center gap-12" onClick={() => go('creator-brief-detail')} style={{
            padding: '10px 12px', background: 'var(--bg-soft)', borderRadius: 10, cursor: 'pointer'
          }}>
            <div style={{ width: 36, height: 36, borderRadius: 9, background: b.color, color: 'white', display: 'grid', placeItems: 'center', fontFamily: 'Space Grotesk', fontWeight: 800 }}>{b.logo}</div>
            <div className="flex-1">
              <div className="bold" style={{ fontSize: 12.5 }}>{b.title}</div>
              <div className="muted" style={{ fontSize: 11 }}>{b.sub}</div>
            </div>
            <div className="font-display bold tabular" style={{ fontSize: 16, color: 'var(--cyan-dark)' }}>{b.match}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── State 1: Pending ──────────────────────────────────────────────
function PendingState({ p, go }) {
  return (
    <>
      <Stepper steps={[
        { label: 'Submitted', when: '12m ago · 3:42pm', state: 'done' },
        { label: 'In review', when: 'DermaQ is looking', state: 'now' },
        { label: 'Shortlist', when: 'avg. within 36h', state: 'todo' },
        { label: 'Decision', when: 'contract + e-sign', state: 'todo' },
      ]} />
      <Banner kind="pending" icon="⏳"
        title="DermaQ is reviewing your application"
        body="Brand opened your profile 4m ago · they typically decide within 48 hours. You can still tweak your pitch or withdraw."
        actions={<>
          <button className="btn btn-ghost btn-sm">Edit pitch</button>
          <button className="btn btn-ghost btn-sm">Withdraw</button>
        </>} />

      <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 14 }}>
        <div>
          <div className="card-elevated" style={{ marginBottom: 14 }}>
            <div className="title-md mb-1">Your submission</div>
            <div className="muted mb-3" style={{ fontSize: 11.5 }}>What DermaQ sees · last edited 12m ago</div>

            <div style={{ display: 'grid', gridTemplateColumns: '110px 1fr', gap: '14px 16px', fontSize: 12.5 }}>
              <div className="cap-label" style={{ fontSize: 9 }}>Deliverable</div>
              <div className="row gap-6" style={{ flexWrap: 'wrap' }}>
                <Pill variant="ink" icon={Icon.tiktok}>1 TikTok 30s video</Pill>
                <Pill variant="ink">Delivers by May 22</Pill>
              </div>

              <div className="cap-label" style={{ fontSize: 9 }}>Asking rate</div>
              <div>
                <span className="font-display bold tabular" style={{ fontSize: 18 }}>${p.rate}</span>
                <span className="muted" style={{ fontSize: 11, marginLeft: 8 }}>USD · within brand band ✓</span>
              </div>

              <div className="cap-label" style={{ fontSize: 9 }}>Your pitch</div>
              <div>
                <p style={{ margin: 0, fontSize: 12.5, lineHeight: 1.5 }}>My audience is HCM 18–24F, 78% female, with strong before/after engagement on skincare. I've worked with 2 acne brands last quarter (DermaPlus, ClearSkin VN) and over-performed CPM by 24%. I can deliver a 30s TikTok by May 22.</p>
                <div className="muted mt-1" style={{ fontSize: 10.5, fontWeight: 600 }}>87 / 100 words</div>
              </div>

              <div className="cap-label" style={{ fontSize: 9 }}>References</div>
              <div className="row gap-6">
                {[['#79FEE7', '#009CFF', '1.2M · 8.4%'], ['#FFC3D6', '#FF6FA3', '820K · 7.1%']].map(([c1, c2, l], i) => (
                  <div key={i} style={{
                    width: 60, height: 84, borderRadius: 8, background: `linear-gradient(135deg, ${c1}, ${c2})`,
                    position: 'relative', overflow: 'hidden'
                  }}>
                    <div style={{ position: 'absolute', bottom: 4, left: 4, right: 4, fontSize: 9, fontWeight: 800, color: 'white', textShadow: '0 1px 3px rgba(0,0,0,0.3)' }}>{l}</div>
                  </div>
                ))}
              </div>
            </div>
          </div>

          <div className="card-elevated">
            <div className="title-md mb-1">Activity</div>
            <div className="muted mb-3" style={{ fontSize: 11.5 }}>Live updates as DermaQ engages</div>
            <ActivityTimeline items={[
              { when: 'Just now · 3:46pm', what: 'Linh (DermaQ marketing lead) opened your profile', who: 'Spent 2m 18s · viewed your TikTok references', icon: '👁', color: 'var(--cyan)' },
              { when: '12m ago · 3:42pm', what: 'Application submitted', who: 'AI fit score locked at 92% · 4 signals matched', icon: '✓', color: 'var(--ink)' },
              { when: '14m ago · 3:40pm', what: 'You started writing the pitch', icon: '✎', color: 'var(--mint-deep)' },
              { when: 'Expected by May 17', what: 'Brand decision · pending', faded: true },
            ]} />
          </div>
        </div>

        <div>
          <BrandSnapshot p={p} />
          <AIFitCard fit={92} />
          <SimilarBriefs go={go} />
        </div>
      </div>
    </>
  );
}

// ── State 2: Shortlisted ──────────────────────────────────────────
function ShortlistedState({ p, go }) {
  const [pickedSlot, setPickedSlot] = React.useState(null);
  return (
    <>
      <Stepper steps={[
        { label: 'Submitted', when: '4d ago', state: 'done' },
        { label: 'In review', when: 'opened 2 times', state: 'done' },
        { label: 'Shortlist call', when: 'action needed', state: 'now' },
        { label: 'Decision', when: 'after sync', state: 'todo' },
      ]} />
      <Banner kind="shortlisted" icon="📅"
        title="Mai (Highland Coffee) wants a 15-min chat"
        body={<>"Loved your aesthetic, want to talk about the 3-SKU shot list." Pick a slot — call goes straight into Google Meet.</>}
        actions={<>
          <button className="btn btn-ghost btn-sm">View message</button>
          <button className="btn btn-primary btn-sm">Schedule sync</button>
        </>} />

      <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 14 }}>
        <div>
          <div className="card-elevated" style={{ marginBottom: 14 }}>
            <div className="title-md mb-1">Pick a time · Mai's calendar</div>
            <div className="muted mb-3" style={{ fontSize: 11.5 }}>Three slots she opened for you · pick one and we'll auto-create a Google Meet</div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10 }}>
              {[
                { d: 'Today', t: '4:30 PM', tag: 'Soonest', tagColor: 'var(--mint-deep)' },
                { d: 'Tomorrow', t: '10:00 AM', tag: 'Recommended', tagColor: 'var(--cyan)' },
                { d: 'Fri May 22', t: '2:15 PM', tag: 'Pre-deadline', tagColor: 'var(--ink-soft)' },
              ].map((s, i) => {
                const isPicked = pickedSlot === i;
                return (
                  <button key={i} onClick={() => setPickedSlot(i)} style={{
                    padding: 14, borderRadius: 12, border: 0, cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left',
                    background: isPicked ? 'rgba(0,156,255,0.06)' : 'var(--bg-soft)',
                    outline: '2px solid ' + (isPicked ? 'var(--cyan)' : 'transparent')
                  }}>
                    <div className="cap-label" style={{ fontSize: 9, color: s.tagColor }}>{s.tag}</div>
                    <div className="font-display bold mt-1" style={{ fontSize: 18, letterSpacing: '-0.015em' }}>{s.d}</div>
                    <div className="bold tabular" style={{ fontSize: 14, marginTop: 2 }}>{s.t}</div>
                    <div className="muted" style={{ fontSize: 10.5, marginTop: 6 }}>15 min · ICT</div>
                  </button>
                );
              })}
            </div>
            <div className="row justify-end mt-4">
              <button className="btn btn-primary btn-sm"
                disabled={pickedSlot === null}
                style={{ opacity: pickedSlot === null ? 0.4 : 1, cursor: pickedSlot === null ? 'not-allowed' : 'pointer' }}>
                {pickedSlot !== null ? 'Confirm slot · open Meet' : 'Pick a slot first'}
              </button>
            </div>
          </div>

          <div className="card-elevated">
            <div className="title-md mb-3">Activity</div>
            <ActivityTimeline items={[
              { when: '1h ago · 9:30am', what: 'Mai shortlisted you', who: '"Best aesthetic out of 12 applicants" — internal note shared with you', icon: '★', color: 'var(--cyan)' },
              { when: 'Yesterday · 4:18pm', what: 'Mai requested a 15-min sync', who: 'Auto-suggested 3 slots from her calendar', icon: '📅', color: 'var(--cyan)' },
              { when: '4d ago', what: 'Application submitted', who: 'AI fit 88% · 3 signals matched', icon: '✓', color: 'var(--ink)' },
            ]} />
          </div>
        </div>

        <div>
          <div className="card-elevated" style={{ marginBottom: 14 }}>
            <div className="title-md mb-2">Meet the brand team</div>
            <div className="row items-center gap-12 mb-3">
              <Avatar name="Mai Nguyễn" size={42} />
              <div className="flex-1">
                <div className="bold">Mai Nguyễn</div>
                <div className="muted" style={{ fontSize: 11 }}>Marketing lead · Highland Coffee</div>
              </div>
              <Pill variant="mint">Fast replier</Pill>
            </div>
            <div className="row items-center gap-12">
              <Avatar name="Hoa Lê" size={42} />
              <div className="flex-1">
                <div className="bold">Hoa Lê</div>
                <div className="muted" style={{ fontSize: 11 }}>Brand director · joins for big sync</div>
              </div>
            </div>
          </div>
          <AIFitCard fit={88} />
        </div>
      </div>
    </>
  );
}

// ── State 3: Accepted ─────────────────────────────────────────────
function AcceptedState({ p, go }) {
  return (
    <>
      <Stepper steps={[
        { label: 'Submitted', when: '2d ago', state: 'done' },
        { label: 'Shortlisted', when: '1d ago', state: 'done' },
        { label: 'Accepted', when: 'Today · 11:02am', state: 'done' },
        { label: 'In production', when: 'Milestone 2 of 4', state: 'now' },
      ]} />
      <Banner kind="accepted" icon="✓"
        title="You're hired · contract signed by both sides"
        body={<>Kick-off paid 25% · $540 already in your wallet. The campaign hub takes over from here — milestones, deliverables and payouts live below.</>}
        actions={<>
          <button className="btn btn-ghost btn-sm">{Icon.external} Contract PDF</button>
          <button className="btn btn-primary btn-sm" onClick={() => go('creator-campaign-kickoff')}>Open project {Icon.arrow}</button>
        </>} />

      <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 14 }}>
        <div>
          <div className="card-elevated" style={{ marginBottom: 14 }}>
            <div className="title-md mb-1">Milestones &amp; payouts</div>
            <div className="muted mb-3" style={{ fontSize: 11.5 }}>4 stages · $2,200 total · auto-paid 24h after each approval</div>

            {[
              { state: 'done', label: 'Kick-off & concept brief', sub: 'Signed contract, brief reviewed', when: 'Done · May 15', pay: 540, paid: true },
              { state: 'now', label: 'Concept & script', sub: '3 reel concepts · 2 looks each', when: 'Due Jun 04 · in 20 days', pay: 440 },
              { state: 'todo', label: 'First reel (15s)', sub: 'First of 3 deliverables', when: 'Due Jun 18', pay: 660 },
              { state: 'todo', label: 'Final 2 reels + post analytics', sub: 'Bundle delivery + 7-day report', when: 'Due Jul 02', pay: 560 },
            ].map((m, i) => (
              <div key={i} className="row items-center gap-12" style={{
                padding: '12px 14px', borderRadius: 12, marginBottom: 6,
                background: m.state === 'now' ? 'rgba(0,156,255,0.06)' : 'var(--bg-soft)',
                border: '1px solid ' + (m.state === 'now' ? 'rgba(0,156,255,0.2)' : 'transparent')
              }}>
                <div style={{
                  width: 32, height: 32, borderRadius: 999,
                  background: m.state === 'done' ? 'var(--mint-deep)' : m.state === 'now' ? 'var(--ink)' : 'white',
                  color: m.state === 'todo' ? 'var(--ink-soft)' : 'white',
                  display: 'grid', placeItems: 'center', fontWeight: 800, fontSize: 12, flexShrink: 0
                }}>{m.state === 'done' ? '✓' : i + 1}</div>
                <div className="flex-1">
                  <div className="bold" style={{ fontSize: 13 }}>{m.label}</div>
                  <div className="muted" style={{ fontSize: 11, marginTop: 1 }}>{m.sub}</div>
                </div>
                <div className="muted text-right" style={{ fontSize: 11 }}>{m.when}</div>
                <div className="font-display bold tabular text-right" style={{ fontSize: 16, minWidth: 80, color: m.paid ? 'var(--mint-deep)' : 'var(--ink)' }}>
                  ${m.pay}{m.paid && <span style={{ display: 'block', fontSize: 10, fontWeight: 700, opacity: 0.8 }}>paid</span>}
                </div>
              </div>
            ))}

            <div className="row justify-end gap-8 mt-4">
              <button className="btn btn-ghost btn-sm">Open chat with brand</button>
              <button className="btn btn-primary btn-sm" onClick={() => go('creator-campaign-upload')}>Upload concept {Icon.arrow}</button>
            </div>
          </div>

          <div className="card-elevated">
            <div className="title-md mb-3">Activity</div>
            <ActivityTimeline items={[
              { when: '2h ago · 11:14am', what: 'Kick-off payment of $540 released to your wallet', icon: '$', color: 'var(--mint-deep)' },
              { when: '3h ago · 11:02am', what: 'Contract signed by you and YODY · escrow funded', icon: '✓', color: 'var(--ink)' },
              { when: 'Yesterday · 4:18pm', what: 'Application accepted by Trang · YODY brand manager', icon: '★', color: 'var(--cyan)' },
            ]} />
          </div>
        </div>

        <div>
          <div className="card-elevated" style={{ marginBottom: 14, padding: 0, overflow: 'hidden' }}>
            <div style={{
              padding: 16, background: 'linear-gradient(135deg, #1FD6B4, #009CFF)', color: 'white'
            }}>
              <div className="row items-center gap-10">
                <div style={{ fontSize: 22 }}>📄</div>
                <div className="flex-1">
                  <div className="bold" style={{ fontSize: 14 }}>Contract · #CT-7710</div>
                  <div style={{ fontSize: 11, opacity: 0.85 }}>Signed by both · escrow funded</div>
                </div>
                <span style={{ color: 'white' }}>{Icon.arrow}</span>
              </div>
            </div>
            <div style={{ padding: '16px 20px' }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px 14px', fontSize: 12 }}>
                <div><div className="cap-label" style={{ fontSize: 9 }}>Total value</div><div className="font-display tabular bold" style={{ fontSize: 18 }}>${p.rate.toLocaleString()}</div></div>
                <div><div className="cap-label" style={{ fontSize: 9 }}>Already paid</div><div className="font-display tabular bold" style={{ fontSize: 18, color: 'var(--mint-deep)' }}>${p.paid}</div></div>
                <div><div className="cap-label" style={{ fontSize: 9 }}>Term</div><div className="bold mt-1">48 days</div></div>
                <div><div className="cap-label" style={{ fontSize: 9 }}>Usage rights</div><div className="bold mt-1">90 days · paid</div></div>
              </div>
            </div>
          </div>

          <div className="card-elevated">
            <div className="title-md mb-3">The brand</div>
            <div className="row items-center gap-12">
              <Avatar name="Trang Phạm" size={48} />
              <div className="flex-1">
                <div className="bold">Trang Phạm</div>
                <div className="muted" style={{ fontSize: 11 }}>Brand Manager · YODY</div>
              </div>
              <button className="btn btn-ghost btn-sm">Message</button>
            </div>
            <div className="row gap-6 mt-3" style={{ flexWrap: 'wrap' }}>
              <Pill variant="mint">Fast payer · 7d avg</Pill>
              <Pill variant="cyan">12 past creators</Pill>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

// ── State 4: Rejected ─────────────────────────────────────────────
function RejectedState({ p, go }) {
  return (
    <>
      <Stepper steps={[
        { label: 'Submitted', when: '1w ago', state: 'done' },
        { label: 'In review', when: 'opened 1 time', state: 'done' },
        { label: 'Shortlist', when: 'skipped', state: 'todo' },
        { label: 'Not selected', when: '5d ago', state: 'fail' },
      ]} />
      <Banner kind="rejected" icon="✕"
        title="Not this time · Saigon Vegan chose another creator"
        body={<>They shared a short note on why · use it to sharpen your next pitch. We've queued up 5 briefs that better match your profile.</>}
        actions={<>
          <button className="btn btn-ghost btn-sm">View feedback</button>
          <button className="btn btn-primary btn-sm" onClick={() => go('creator-discover')}>Browse similar briefs {Icon.arrow}</button>
        </>} />

      <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 14 }}>
        <div>
          <div className="card-elevated" style={{ marginBottom: 14 }}>
            <div className="title-md mb-1">Brand feedback</div>
            <div className="muted mb-3" style={{ fontSize: 11.5 }}>Saigon Vegan · private to you · not visible on your public profile</div>

            <div style={{ padding: 18, background: 'var(--bg-soft)', borderRadius: 12, position: 'relative' }}>
              <div className="row items-center gap-10 mb-2">
                <div style={{ width: 34, height: 34, borderRadius: 9, background: 'var(--mint-deep)', color: 'white', display: 'grid', placeItems: 'center', fontFamily: 'Space Grotesk', fontWeight: 800 }}>S</div>
                <div>
                  <div className="bold" style={{ fontSize: 13 }}>Notes from Hà</div>
                  <div className="muted" style={{ fontSize: 11 }}>Saigon Vegan · Brand director</div>
                </div>
              </div>
              <p style={{ margin: '8px 0 0', fontSize: 13, lineHeight: 1.6, fontStyle: 'italic' }}>
                "Loved your skincare reels, but our hero spot needs strong food-styling and on-cam tasting. Looking for a creator with proven F&amp;B portfolio. Definitely watch for our next launch — you'd fit a wellness brief."
              </p>
            </div>

            <div className="cap-label mt-6 mb-2">What this means for your matching</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              {[
                ['F&B briefs slightly downweighted', 'until you build food-styling work'],
                ['Wellness + skincare briefs prioritized', 'matches your strongest signals'],
                ['Saigon Vegan still in your network', 'they may invite you to a future brief']
              ].map(([l, sub], i) => (
                <div key={i} className="row items-start gap-10" style={{ padding: '8px 0' }}>
                  <span style={{ marginTop: 4, width: 6, height: 6, borderRadius: 999, background: 'var(--cyan)', flexShrink: 0 }} />
                  <div>
                    <div className="bold" style={{ fontSize: 12.5 }}>{l}</div>
                    <div className="muted" style={{ fontSize: 11 }}>{sub}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>

          <div className="card-elevated">
            <div className="title-md mb-3">Activity</div>
            <ActivityTimeline items={[
              { when: '5d ago', what: 'Not selected · Saigon Vegan picked a F&B-native creator', who: 'Brand left feedback for you', icon: '✕', color: 'var(--pink-hot)' },
              { when: '6d ago', what: 'Hà opened your profile', who: 'Spent 38s · viewed 1 reference', icon: '👁', color: 'var(--cyan)' },
              { when: '1w ago', what: 'Application submitted', who: 'AI fit 64% · 2 signals matched', icon: '✓', color: 'var(--ink)' },
            ]} />
          </div>
        </div>

        <div>
          <SimilarBriefs go={go} title="Recovery picks" sub="5 better-fit briefs · open this week" />

          <div className="card-elevated mt-6" style={{ padding: 16, background: 'rgba(0,156,255,0.05)', border: '1px solid rgba(0,156,255,0.2)' }}>
            <div className="row items-center gap-10 mb-2">
              <span style={{ fontSize: 22 }}>💡</span>
              <div className="bold" style={{ fontSize: 13 }}>Quick wins to lift your match score</div>
            </div>
            <ul style={{ fontSize: 12, lineHeight: 1.6, paddingLeft: 18, margin: '6px 0 0', color: 'var(--ink-soft)' }}>
              <li>Pin one F&amp;B-style reel to your media kit</li>
              <li>Add &quot;food&quot; + &quot;wellness&quot; tags to your bio</li>
              <li>Update your rate card — your current is +24% vs market</li>
            </ul>
            <button className="btn btn-primary btn-sm mt-3" style={{ width: '100%' }} onClick={() => go('creator-profile')}>Open media kit {Icon.arrow}</button>
          </div>
        </div>
      </div>
    </>
  );
}

// ── Main screen ───────────────────────────────────────────────────
function ScreenCreatorApplicationDetail() {
  const { t } = useT();
  const { go } = useRouter();
  // Read from window so Applications list can set context before navigating; default 'pending'.
  const [status, setStatus] = React.useState(() => window.__appStatus || 'pending');
  const p = APP_PROFILES[status];

  const heroRight = {
    pending:     { label: 'Your rate',  value: '$' + p.rate.toLocaleString(), sub: 'applied ' + p.applied },
    shortlisted: { label: 'Your rate',  value: '$' + p.rate.toLocaleString(), sub: 'applied ' + p.applied },
    accepted:    { label: 'Locked rate', value: '$' + p.rate.toLocaleString(), sub: '$' + p.paid + ' already paid' },
    rejected:    { label: 'You asked',  value: '$' + p.rate.toLocaleString(), sub: 'applied ' + p.applied },
  }[status];

  return (
    <div className="app-shell" data-portal="creator">
      <AppSidebar portal="creator" active="creator-applications" />
      <main className="main">
        <AppTopbar showNewBrief={false} user="L" />

        <div className="row items-center gap-6 muted mb-4" style={{ fontSize: 12 }}>
          <a onClick={() => go('creator-applications')} style={{ cursor: 'pointer' }}>{t('creator.applications.title')}</a>
          <span>›</span>
          <span className="bold" style={{ color: 'var(--ink)' }}>{p.brand} · {p.title}</span>
        </div>

        <div className="row items-center justify-between mb-4">
          <h1 className="page-title" style={{ margin: 0 }}>Application detail</h1>
          {/* Status switcher — same screen, 4 shapes */}
          <div className="row gap-4" style={{ padding: 3, background: 'var(--bg-soft)', borderRadius: 999 }}>
            {[
              ['pending', 'Pending', 'var(--yellow-deep)'],
              ['shortlisted', 'Shortlisted', 'var(--cyan)'],
              ['accepted', 'Accepted', 'var(--mint-deep)'],
              ['rejected', 'Not selected', 'var(--pink-hot)'],
            ].map(([k, l, c]) => (
              <button key={k} onClick={() => { setStatus(k); window.__appStatus = k; }} style={{
                padding: '7px 14px', borderRadius: 999, border: 0, cursor: 'pointer', fontFamily: 'inherit',
                background: status === k ? 'white' : 'transparent',
                color: status === k ? c : 'var(--ink-soft)',
                fontWeight: 700, fontSize: 12,
                boxShadow: status === k ? '0 1px 3px rgba(0,43,80,0.1)' : 'none'
              }}>{l}</button>
            ))}
          </div>
        </div>

        <Hero p={p}
          rightLabel={heroRight.label}
          rightValue={heroRight.value}
          rightSub={heroRight.sub}
          badge={status === 'accepted' ? <Pill variant="mint" icon={Icon.check}>Project active</Pill> : status === 'shortlisted' ? <Pill variant="mint">★ Shortlisted</Pill> : null} />

        {status === 'pending'     && <PendingState     p={p} go={go} />}
        {status === 'shortlisted' && <ShortlistedState p={p} go={go} />}
        {status === 'accepted'    && <AcceptedState    p={p} go={go} />}
        {status === 'rejected'    && <RejectedState    p={p} go={go} />}
      </main>
    </div>
  );
}

Object.assign(window, { ScreenCreatorApplicationDetail });
