/* screen-creator-pages-a.jsx — Creator Discover + Brief Detail + Applications */
/* global React, AppSidebar, AppTopbar, useRouter, useT, Counter, Sparkline, Avatar, Pill, MatchCircle, Icon, useInView */

// ── Discover briefs (marketplace) ──────────────────────────────────
const OPEN_BRIEFS = [
  { id: 'BO-4019', brand: 'DermaQ', logo: 'D', color: 'var(--cyan)', title: 'Acne care · awareness video', match: 92, budget: [1.2, 2.4], deadline: '2d', cat: 'Skincare', platform: 'tiktok', applicants: 18, brief: 'Looking for honest, mid-tier skincare creators with strong before/after content history.' },
  { id: 'BO-4018', brand: 'YODY', logo: 'Y', color: 'var(--pink-hot)', title: 'Tet 2026 fashion drop', match: 84, budget: [1.8, 3.6], deadline: '5d', cat: 'Fashion', platform: 'instagram', applicants: 42, brief: 'IG reels showcasing Tet collection in HCM/HN urban context.' },
  { id: 'BO-4017', brand: 'Saigon Vegan', logo: 'S', color: 'var(--mint-deep)', title: 'Vegan snack hero spot', match: 78, budget: [0.8, 1.6], deadline: '9d', cat: 'Food · Wellness', platform: 'tiktok', applicants: 12, brief: 'Plant-based protein bars — looking for wellness creators.' },
  { id: 'BO-4015', brand: 'Xiaomi VN', logo: 'X', color: 'var(--indigo)', title: 'Smart home unboxing', match: 65, budget: [2.0, 4.0], deadline: '14d', cat: 'Tech', platform: 'youtube', applicants: 8, brief: 'Long-form unboxing for Xiaomi Smart Home Mi Box.' },
  { id: 'BO-4014', brand: 'Highland Coffee', logo: 'H', color: 'var(--coral)', title: 'New espresso flight', match: 88, budget: [1.0, 2.0], deadline: '7d', cat: 'Food', platform: 'instagram', applicants: 24, brief: 'Aesthetic shots + tasting note vlog · 3 SKUs.' },
  { id: 'BO-4013', brand: 'Vinamilk', logo: 'V', color: 'var(--yellow-deep)', title: 'Kids back-to-school', match: 56, budget: [1.5, 2.8], deadline: '21d', cat: 'Parenting', platform: 'instagram', applicants: 34, brief: 'Family-friendly content for school-age kids dairy drinks.' },
];

function ScreenCreatorDiscover() {
  const { t } = useT();
  const { go } = useRouter();
  const [sort, setSort] = React.useState('match');

  return (
    <div className="app-shell" data-portal="creator">
      <AppSidebar portal="creator" active="creator-discover" />
      <main className="main">
        <AppTopbar showNewBrief={false} user="L" />
        <div className="row items-end justify-between mb-6">
          <div>
            <span className="pill pill-mint">{OPEN_BRIEFS.length} open · 3 closing soon</span>
            <h1 className="page-title" style={{ marginTop: 8 }}>{t('creator.discover.title')}</h1>
            <div className="page-subtitle">{t('creator.discover.subtitle')}</div>
          </div>
          <div className="row gap-8">
            <select className="input" style={{ width: 160, padding: '8px 12px' }} value={sort} onChange={e => setSort(e.target.value)}>
              <option value="match">Best match</option>
              <option value="budget">Highest budget</option>
              <option value="deadline">Closing soonest</option>
            </select>
            <button className="btn btn-ghost btn-sm">{Icon.sliders} Filters</button>
          </div>
        </div>

        {/* Filter chips */}
        <div className="row items-center gap-8 mb-4" style={{ flexWrap: 'wrap' }}>
          <span className="cap-label">Categories:</span>
          {['Skincare', 'Beauty', 'Fashion', 'Food', 'Wellness', 'Tech', 'Lifestyle'].map((c, i) => (
            <button key={c} style={{
              padding: '6px 12px',
              borderRadius: 999,
              border: '1.5px solid ' + (i < 3 ? 'var(--ink)' : 'var(--line)'),
              background: i < 3 ? 'var(--ink)' : 'white',
              color: i < 3 ? 'white' : 'var(--ink)',
              fontSize: 12, fontWeight: 700, fontFamily: 'inherit', cursor: 'pointer'
            }}>{c}</button>
          ))}
        </div>

        {/* Grid */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(360px, 1fr))', gap: 14 }}>
          {OPEN_BRIEFS.map((b, i) => (
            <div key={b.id} className="card-elevated" style={{ padding: 0, overflow: 'hidden', cursor: 'pointer',
              animation: `cardIn .5s ${i * 80}ms backwards cubic-bezier(.4,0,.2,1)` }}
              onClick={() => go('creator-brief-detail')}>
              <div style={{ height: 4, background: b.color }} />
              <div style={{ padding: 18 }}>
                <div className="row items-center gap-12 mb-2">
                  <div style={{
                    width: 44, height: 44, borderRadius: 12,
                    background: b.color, color: 'white',
                    display: 'grid', placeItems: 'center',
                    fontFamily: 'Space Grotesk', fontWeight: 800, fontSize: 18
                  }}>{b.logo}</div>
                  <div className="flex-1">
                    <div className="bold" style={{ fontSize: 13 }}>{b.brand}</div>
                    <div className="muted" style={{ fontSize: 11 }}>{b.id} · {b.deadline} left</div>
                  </div>
                  <MatchCircle score={b.match} size={48} />
                </div>
                <div className="font-display bold" style={{ fontSize: 17, letterSpacing: '-0.015em', marginTop: 4 }}>{b.title}</div>
                <div className="muted" style={{ fontSize: 12, marginTop: 6, lineHeight: 1.5 }}>{b.brief}</div>
                <div className="row gap-4 mt-3" style={{ flexWrap: 'wrap' }}>
                  <Pill variant="lav">{b.cat}</Pill>
                  <Pill variant="cyan">{b.platform === 'tiktok' ? <>{Icon.tiktok} TikTok</> : b.platform === 'instagram' ? <>{Icon.instagram} IG</> : <>{Icon.youtube} YT</>}</Pill>
                </div>
                <div className="row items-end justify-between mt-4" style={{ paddingTop: 14, borderTop: '1px solid var(--line)' }}>
                  <div>
                    <div className="cap-label" style={{ fontSize: 9 }}>Budget</div>
                    <div className="font-display bold tabular" style={{ fontSize: 18 }}>${b.budget[0]}K – ${b.budget[1]}K</div>
                  </div>
                  <div className="text-right">
                    <div className="muted" style={{ fontSize: 11 }}>{b.applicants} applied</div>
                    <button className="btn btn-primary btn-sm mt-2" onClick={(e) => { e.stopPropagation(); go('creator-brief-detail'); }}>Apply {Icon.arrow}</button>
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
        <style>{`@keyframes cardIn { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }`}</style>
      </main>
    </div>
  );
}

// ── Brief detail + Apply form ───────────────────────────────────────
function ScreenCreatorBriefDetail() {
  const { t } = useT();
  const { go } = useRouter();
  const [applying, setApplying] = React.useState(false);

  return (
    <div className="app-shell" data-portal="creator">
      <AppSidebar portal="creator" active="creator-discover" />
      <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-discover')} style={{ cursor: 'pointer' }}>{t('creator.discover.title')}</a>
          <span>·</span>
          <span className="bold" style={{ color: 'var(--ink)' }}>Acne care · awareness video</span>
        </div>

        {/* Hero */}
        <div className="card-elevated" style={{ padding: 28, background: 'linear-gradient(135deg, #79FEE7 0%, #009CFF 110%)', color: 'var(--ink)', position: 'relative', overflow: 'hidden' }}>
          <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-24" style={{ position: 'relative', zIndex: 1 }}>
            <div style={{
              width: 80, height: 80, borderRadius: 18,
              background: 'white', color: 'var(--ink)',
              display: 'grid', placeItems: 'center',
              fontFamily: 'Space Grotesk', fontWeight: 800, fontSize: 32,
              boxShadow: '0 10px 24px rgba(0,43,80,0.2)'
            }}>D</div>
            <div className="flex-1">
              <Pill variant="dark">DermaQ · Skincare brand</Pill>
              <h1 className="font-display" style={{ fontSize: 36, fontWeight: 700, margin: '8px 0 0', letterSpacing: '-0.025em', lineHeight: 1.1 }}>
                Acne care · awareness video
              </h1>
              <div className="row gap-6 mt-3">
                <Pill variant="dark">{Icon.tiktok} TikTok</Pill>
                <Pill variant="dark">$1.2K – $2.4K</Pill>
                <Pill variant="dark">2 days left</Pill>
                <Pill variant="dark">18 applied</Pill>
              </div>
            </div>
            <div className="text-center">
              <MatchCircle score={92} size={88} />
              <div className="cap-label mt-2">Your match</div>
            </div>
          </div>
        </div>

        {/* Apply CTA strip */}
        <div className="row items-center gap-16 mt-6 mb-6" style={{
          padding: '14px 20px',
          background: 'var(--ink)', color: 'white', borderRadius: 14
        }}>
          <div className="flex-1">
            <div className="bold">Ready to apply?</div>
            <div style={{ fontSize: 12, opacity: 0.7 }}>Submission takes 2 minutes. Brand responds within 48 hours.</div>
          </div>
          <button className="btn btn-yellow" onClick={() => setApplying(a => !a)}>
            {applying ? 'Hide form' : <>Apply now {Icon.arrow}</>}
          </button>
        </div>

        {/* Apply form (when toggled) */}
        {applying && <ApplyForm onCancel={() => setApplying(false)} />}

        {/* Main content */}
        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 14 }}>
          <div className="card-elevated">
            <div className="title-md mb-3">The brief</div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 18 }}>
              <div><div className="cap-label">Goal</div><div className="bold mt-1" style={{ fontSize: 14 }}>Drive awareness for new acne-care launch</div></div>
              <div><div className="cap-label">Audience</div><div className="bold mt-1" style={{ fontSize: 14 }}>HCM/HN · 18–24F · concern: acne</div></div>
              <div><div className="cap-label">Timeline</div><div className="bold mt-1" style={{ fontSize: 14 }}>May 14 – Jun 11</div></div>
              <div><div className="cap-label">Deliverables</div><div className="bold mt-1" style={{ fontSize: 14 }}>1 TikTok video + 1 follow-up</div></div>
            </div>

            <div className="cap-label mb-2">Requirements</div>
            <div className="row gap-6 mb-4" style={{ flexWrap: 'wrap' }}>
              <Pill variant="lav">Honest before/after</Pill>
              <Pill variant="lav">No filter heavy</Pill>
              <Pill variant="lav">Mention "DermaQ"</Pill>
              <Pill variant="lav">Hashtag #SkinReset</Pill>
              <Pill variant="lav">Disclosure required</Pill>
            </div>

            <div className="cap-label mb-2">Brand assets provided</div>
            <div className="row gap-8">
              {['Product brief', 'Color guide', 'Logo SVG', 'Sample script'].map((a, i) => (
                <div key={a} style={{
                  padding: 12, background: 'var(--bg-soft)', borderRadius: 10,
                  flex: 1, display: 'flex', alignItems: 'center', gap: 8
                }}>
                  <div style={{ width: 24, height: 24, borderRadius: 6, background: 'white', display: 'grid', placeItems: 'center', color: 'var(--ink-soft)' }}>{Icon.file}</div>
                  <span style={{ fontSize: 12, fontWeight: 600 }}>{a}</span>
                </div>
              ))}
            </div>
          </div>

          <div className="card-elevated">
            <div className="title-md mb-3">Why you&rsquo;re a 92% match</div>
            <div className="cap-label mb-2">AI breakdown</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {[
                { l: 'Audience overlap (HCM 18–24F)', v: 96, c: 'var(--mint-deep)' },
                { l: 'Category match (Skincare)', v: 94, c: 'var(--cyan)' },
                { l: 'ER vs target threshold', v: 88, c: 'var(--indigo)' },
                { l: 'Past performance same vertical', v: 92, c: 'var(--pink-hot)' },
              ].map((p, i) => (
                <div key={i}>
                  <div className="row items-center justify-between mb-1">
                    <span style={{ fontSize: 12, fontWeight: 600 }}>{p.l}</span>
                    <span className="tabular bold" style={{ fontSize: 12 }}>{p.v}%</span>
                  </div>
                  <div style={{ height: 6, background: 'var(--bg-soft)', borderRadius: 999, overflow: 'hidden' }}>
                    <div style={{ height: '100%', width: p.v + '%', background: p.c, borderRadius: 999, transformOrigin: 'left',
                      animation: `grow-w 1s ${0.3 + i * 0.1}s cubic-bezier(.4,0,.2,1) both`, transform: 'scaleX(0)' }} />
                  </div>
                </div>
              ))}
            </div>
            <div className="card mt-6" style={{ padding: 14, background: 'var(--bg-soft)', fontSize: 12, lineHeight: 1.5 }}>
              <div className="cap-label" style={{ fontSize: 9 }}><span style={{ color: 'var(--pink-hot)' }}>●</span> AI says</div>
              <div className="mt-2">Strong fit. Your last 3 skincare posts averaged 6.4% ER, well above the brand&rsquo;s 4% threshold. Audience overlap on HCM 18–24F is high.</div>
            </div>
          </div>
        </div>
      </main>
    </div>
  );
}

// ── Applications list ─────────────────────────────────────────────
function ScreenCreatorApplications() {
  const { t } = useT();
  const { go } = useRouter();
  const apps = [
    { brand: 'DermaQ', title: 'Acne care · awareness video', status: 'pending', applied: '12m ago', rate: 1800, color: 'var(--cyan)' },
    { brand: 'YODY', title: 'Tet 2026 fashion drop', status: 'accepted', applied: '2d ago', rate: 2200, color: 'var(--pink-hot)' },
    { brand: 'Highland Coffee', title: 'New espresso flight', status: 'shortlisted', applied: '4d ago', rate: 1400, color: 'var(--coral)' },
    { brand: 'Saigon Vegan', title: 'Vegan snack hero spot', status: 'rejected', applied: '1w ago', rate: 1200, color: 'var(--mint-deep)' },
    { brand: 'Xiaomi VN', title: 'Smart home unboxing', status: 'shortlisted', applied: '1w ago', rate: 2800, color: 'var(--indigo)' },
    { brand: 'Vinamilk', title: 'Kids back-to-school', status: 'pending', applied: '2w ago', rate: 1600, color: 'var(--yellow-deep)' },
  ];
  const counts = {
    all: apps.length,
    pending: apps.filter(a => a.status === 'pending').length,
    shortlisted: apps.filter(a => a.status === 'shortlisted').length,
    accepted: apps.filter(a => a.status === 'accepted').length,
    rejected: apps.filter(a => a.status === 'rejected').length,
  };
  const [filter, setFilter] = React.useState('all');
  const filtered = filter === 'all' ? apps : apps.filter(a => a.status === filter);

  return (
    <div className="app-shell" data-portal="creator">
      <AppSidebar portal="creator" active="creator-applications" />
      <main className="main">
        <AppTopbar showNewBrief={false} user="L" />
        <h1 className="page-title">{t('creator.applications.title')}</h1>
        <div className="page-subtitle">{t('creator.applications.subtitle')} · once awarded, campaigns move to <a onClick={() => go('creator-campaigns')} style={{ color: 'var(--cyan-dark)', cursor: 'pointer', fontWeight: 700 }}>My campaigns</a></div>

        {/* Summary */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 10, marginTop: 24 }}>
          {[
            { l: 'Total', v: counts.all, c: 'var(--ink)' },
            { l: 'Pending', v: counts.pending, c: 'var(--yellow-deep)' },
            { l: 'Shortlisted', v: counts.shortlisted, c: 'var(--cyan)' },
            { l: 'Accepted', v: counts.accepted, c: 'var(--mint-deep)' },
            { l: 'Rejected', v: counts.rejected, c: 'var(--ink-soft)' },
          ].map((k, i) => (
            <button key={i} onClick={() => setFilter(['all','pending','shortlisted','accepted','rejected'][i])}
              style={{
                padding: 18, borderRadius: 14,
                background: 'white',
                border: '2px solid ' + (filter === ['all','pending','shortlisted','accepted','rejected'][i] ? 'var(--ink)' : 'var(--line)'),
                textAlign: 'left', fontFamily: 'inherit', cursor: 'pointer'
              }}>
              <div className="cap-label">{k.l}</div>
              <div className="font-display bold tabular" style={{ fontSize: 32, color: k.c, marginTop: 4 }}>{k.v}</div>
            </button>
          ))}
        </div>

        {/* List */}
        <div className="card-elevated mt-6" style={{ padding: 0, overflow: 'hidden' }}>
          <table className="tbl">
            <thead>
              <tr>
                <th>Brief</th>
                <th>Status</th>
                <th className="text-right">Your rate</th>
                <th>Applied</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((a, i) => {
                const isAccepted = a.status === 'accepted';
                return (
                  <tr key={i} style={{ cursor: 'pointer' }}
                    onClick={() => { window.__appStatus = a.status; go('creator-application-detail'); }}>
                    <td>
                      <div className="row items-center gap-12">
                        <div style={{
                          width: 40, height: 40, borderRadius: 10,
                          background: a.color, color: 'white',
                          display: 'grid', placeItems: 'center',
                          fontFamily: 'Space Grotesk', fontWeight: 800
                        }}>{a.brand.charAt(0)}</div>
                        <div>
                          <div className="bold" style={{ fontSize: 13 }}>{a.title}</div>
                          <div className="muted" style={{ fontSize: 11 }}>{a.brand}</div>
                        </div>
                      </div>
                    </td>
                    <td>
                      {isAccepted
                        ? <Pill variant="mint" icon={Icon.check}>Awarded · ready to start</Pill>
                        : <StatusFlow current={a.status} />}
                    </td>
                    <td className="text-right">
                      <div className="font-display bold tabular" style={{ fontSize: 14 }}>${a.rate}</div>
                    </td>
                    <td className="muted" style={{ fontSize: 12 }}>{a.applied}</td>
                    <td className="text-right">
                      {isAccepted
                        ? <button className="btn btn-primary btn-sm" onClick={(e) => { e.stopPropagation(); go('creator-campaign-kickoff'); }}>Start campaign {Icon.arrow}</button>
                        : <span style={{ color: 'var(--ink-soft)' }}>{Icon.arrow}</span>}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </main>
    </div>
  );
}

function StatusFlow({ current }) {
  const stages = ['pending', 'shortlisted', 'accepted'];
  const idx = current === 'rejected' ? -1 : stages.indexOf(current);
  if (current === 'rejected') {
    return <Pill variant="pink">Not selected</Pill>;
  }
  return (
    <div className="row items-center gap-4" style={{ minWidth: 200 }}>
      {stages.map((s, i) => (
        <React.Fragment key={s}>
          <div style={{
            width: 18, height: 18, borderRadius: 999,
            background: i <= idx ? (i === idx ? 'var(--ink)' : 'var(--mint)') : 'var(--bg-soft)',
            color: i <= idx ? (i === idx ? 'white' : 'var(--ink)') : 'var(--ink-soft)',
            display: 'grid', placeItems: 'center',
            fontSize: 9, fontWeight: 800
          }}>{i < idx ? '✓' : i + 1}</div>
          <span style={{
            fontSize: 11, fontWeight: 700,
            color: i === idx ? 'var(--ink)' : 'var(--ink-soft)',
            textTransform: 'capitalize'
          }}>{s}</span>
          {i < stages.length - 1 && <div style={{ width: 16, height: 2, background: i < idx ? 'var(--mint)' : 'var(--bg-soft)', margin: '0 2px' }} />}
        </React.Fragment>
      ))}
    </div>
  );
}

Object.assign(window, { ScreenCreatorDiscover, ScreenCreatorBriefDetail, ScreenCreatorApplications });
