// screen-publishing.jsx — Publishing wizard with uniqueness score animation
// Exports: PublishingScreen

const PublishingScreen = ({ persona, tweaks }) => {
  const [wizardOpen, setWizardOpen] = React.useState(false);
  const { dark } = tweaks;

  const cardBg = dark ? 'rgba(255,255,255,0.06)' : 'var(--white)';
  const cardBorder = dark ? 'rgba(255,255,255,0.1)' : 'var(--hairline)';
  const textColor = dark ? 'rgba(245,241,232,0.9)' : 'var(--fg-1)';
  const subColor = dark ? 'rgba(245,241,232,0.5)' : 'var(--fg-3)';

  const iosStatus = persona.id === 'nour' ? 'in review' : 'live';
  const androidStatus = persona.id === 'nour' ? 'building' : 'live';
  const version = persona.id === 'nour' ? '1.0.0' : '2.4.1';

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 24, maxWidth: 860 }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16 }}>
        <div>
          <h1 style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 32, color: textColor, margin: 0 }}>Publishing</h1>
          <div style={{ fontSize: 13, color: subColor, marginTop: 6 }}>App Store & Google Play status, build history, and uniqueness score.</div>
        </div>
        <window.Button icon="upload-cloud" onClick={() => setWizardOpen(true)}>
          {persona.id === 'nour' ? 'Publish update' : 'Submit update'}
        </window.Button>
      </div>

      {/* Status cards */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        {[
          { store: 'App Store', icon: 'apple', status: iosStatus, version, updated: persona.id === 'nour' ? 'Submitted Jun 6' : 'Updated May 28', installs: persona.id === 'nour' ? '—' : '2,840', rating: persona.id === 'nour' ? '—' : '4.8' },
          { store: 'Google Play', icon: 'play', status: androidStatus, version, updated: persona.id === 'nour' ? 'Building now' : 'Updated May 28', installs: persona.id === 'nour' ? '—' : '1,007', rating: persona.id === 'nour' ? '—' : '4.7' },
        ].map(store => (
          <div key={store.store} style={{ background: cardBg, border: `1px solid ${cardBorder}`, borderRadius: 14, padding: 24 }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <div style={{ width: 36, height: 36, borderRadius: 9, background: dark ? 'rgba(255,255,255,0.08)' : 'var(--ink)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <i data-lucide={store.icon === 'apple' ? 'smartphone' : 'play'} style={{ width: 18, height: 18, color: dark ? 'var(--paper)' : 'var(--paper)' }}></i>
                </div>
                <div>
                  <div style={{ fontSize: 14, fontWeight: 600, color: textColor }}>{store.store}</div>
                  <div style={{ fontSize: 11, color: subColor }}>v{store.version}</div>
                </div>
              </div>
              <window.StatusPill status={store.status} />
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              {[
                { label: 'Installs', val: store.installs },
                { label: 'Rating', val: store.rating },
                { label: 'Last updated', val: store.updated },
                { label: 'Version', val: `v${store.version}` },
              ].map(item => (
                <div key={item.label}>
                  <div style={{ fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', color: subColor, fontWeight: 500, marginBottom: 4 }}>{item.label}</div>
                  <div style={{ fontSize: 14, fontWeight: 500, color: textColor, fontFamily: item.label === 'Installs' || item.label === 'Rating' || item.label === 'Version' ? 'var(--font-mono)' : 'var(--font-ui)' }}>{item.val}</div>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>

      {/* Uniqueness score */}
      <div style={{ background: cardBg, border: `1px solid ${cardBorder}`, borderRadius: 14, padding: 28 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 20 }}>
          <div>
            <div style={{ fontSize: 13, fontWeight: 600, color: textColor }}>App uniqueness score</div>
            <div style={{ fontSize: 12, color: subColor, marginTop: 3 }}>Apple requires ≥ 70% to pass Guideline 4.2</div>
          </div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 4 }}>
            <span style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 42, lineHeight: 1, color: 'var(--mint)' }}>78%</span>
            <span style={{ fontSize: 12, color: 'var(--mint)', fontWeight: 500 }}>✓ Above threshold</span>
          </div>
        </div>
        <div style={{ height: 8, background: 'var(--sand-100)', borderRadius: 999, overflow: 'hidden', marginBottom: 16 }}>
          <div style={{ height: '100%', width: '78%', background: 'var(--mint)', borderRadius: 999 }}></div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10 }}>
          {[
            { label: 'Unique branding', score: 100, ok: true },
            { label: 'Custom content', score: 85, ok: true },
            { label: 'Native features', score: 70, ok: true },
            { label: 'App metadata', score: 60, ok: true },
          ].map(item => (
            <div key={item.label} style={{ background: dark ? 'rgba(255,255,255,0.04)' : 'var(--sand-50)', borderRadius: 8, padding: '12px 14px' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 8 }}>
                <i data-lucide={item.ok ? 'check-circle' : 'alert-circle'} style={{ width: 13, height: 13, color: item.ok ? 'var(--mint)' : 'var(--amber)' }}></i>
                <span style={{ fontSize: 11, fontWeight: 500, color: textColor }}>{item.label}</span>
              </div>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 18, fontWeight: 600, color: item.ok ? textColor : 'var(--amber)' }}>{item.score}%</div>
            </div>
          ))}
        </div>
      </div>

      {/* Build history */}
      <div style={{ background: cardBg, border: `1px solid ${cardBorder}`, borderRadius: 12, overflow: 'hidden' }}>
        <div style={{ padding: '16px 20px', borderBottom: `1px solid ${cardBorder}`, fontSize: 13, fontWeight: 600, color: textColor }}>Build history</div>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
          <thead>
            <tr>{['Build', 'Platform', 'Version', 'Started', 'Duration', 'Status'].map(h => (
              <th key={h} style={{ textAlign: 'left', padding: '10px 16px', fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', color: subColor, fontWeight: 500, borderBottom: `1px solid ${cardBorder}`, background: dark ? 'rgba(0,0,0,0.1)' : 'var(--paper-bright)' }}>{h}</th>
            ))}</tr>
          </thead>
          <tbody>
            {[
              { id: '#B-0042', platform: 'iOS', version: '1.0.0', started: 'Jun 6, 14:22', dur: '8m 14s', status: 'in review' },
              { id: '#B-0041', platform: 'Android', version: '1.0.0', started: 'Jun 6, 14:20', dur: '6m 02s', status: persona.id === 'nour' ? 'building' : 'live' },
              { id: '#B-0038', platform: 'iOS', version: '0.9.8', started: 'Jun 2, 10:08', dur: '9m 31s', status: persona.id === 'nour' ? 'rejected' : 'live' },
              { id: '#B-0037', platform: 'Android', version: '0.9.8', started: 'Jun 2, 10:06', dur: '5m 48s', status: 'live' },
            ].map((b, i, arr) => (
              <tr key={b.id} style={{ borderBottom: i < arr.length - 1 ? `1px solid ${dark ? 'rgba(255,255,255,0.05)' : 'var(--hairline-soft)'}` : 'none' }}>
                <td style={{ padding: '12px 16px', fontFamily: 'var(--font-mono)', fontSize: 12, color: textColor }}>{b.id}</td>
                <td style={{ padding: '12px 16px', color: textColor }}>{b.platform}</td>
                <td style={{ padding: '12px 16px', fontFamily: 'var(--font-mono)', fontSize: 12, color: textColor }}>v{b.version}</td>
                <td style={{ padding: '12px 16px', fontSize: 12, color: subColor }}>{b.started}</td>
                <td style={{ padding: '12px 16px', fontFamily: 'var(--font-mono)', fontSize: 12, color: subColor }}>{b.dur}</td>
                <td style={{ padding: '12px 16px' }}><window.StatusPill status={b.status} /></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {wizardOpen && <PublishWizard onClose={() => setWizardOpen(false)} persona={persona} />}
    </div>
  );
};

// Publish wizard modal
const PublishWizard = ({ onClose, persona }) => {
  const [step, setStep] = React.useState(1);
  const [score, setScore] = React.useState(0);
  const [building, setBuilding] = React.useState(false);
  const [done, setDone] = React.useState(false);
  const STEPS = ['App identity', 'Developer accounts', 'Uniqueness check', 'Submit'];

  React.useEffect(() => {
    if (step !== 3) return;
    setScore(0);
    const target = 78;
    let current = 0;
    const interval = setInterval(() => {
      current = Math.min(target, current + Math.floor(Math.random() * 4) + 2);
      setScore(current);
      if (current >= target) clearInterval(interval);
    }, 40);
    return () => clearInterval(interval);
  }, [step]);

  const handleSubmit = () => {
    setBuilding(true);
    setTimeout(() => { setBuilding(false); setDone(true); }, 2200);
  };

  const content = {
    1: (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
        <window.Input label="App name (App Store & Google Play)" value={persona.appName} help="This is what customers see in the app stores." />
        <window.Input label="App subtitle" value={persona.id === 'nour' ? 'Fashion from Cairo' : 'Premium electronics'} />
        <window.Textarea label="App description" value={persona.id === 'nour' ? 'Shop the latest fashion from Nour Cairo — silk scarves, linen abayas, and more. Native checkout with Apple Pay.' : 'Shop premium electronics from Marcus. Pro earbuds, studio speakers, and accessories. Fast shipping.'} rows={3} />
        <div style={{ display: 'flex', gap: 16 }}>
          <window.Input label="Primary category" value={persona.id === 'nour' ? 'Shopping' : 'Shopping'} style={{ flex: 1 }} />
          <window.Input label="Age rating" value="4+" style={{ flex: 1 }} />
        </div>
      </div>
    ),
    2: (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        {[
          { store: 'Apple Developer Account', icon: 'smartphone', status: persona.id === 'marcus', note: persona.id === 'nour' ? 'Required for App Store submission. Annual fee: $99/year.' : 'Connected — Team ID: 8ZJ49A2B4X' },
          { store: 'Google Play Console', icon: 'play', status: persona.id === 'marcus', note: persona.id === 'nour' ? 'Required for Google Play. One-time fee: $25.' : 'Connected — Package: com.marcuselectronics.app' },
        ].map(acc => (
          <div key={acc.store} style={{ display: 'flex', alignItems: 'flex-start', gap: 14, padding: 16, background: 'var(--paper)', borderRadius: 10, border: '1px solid var(--hairline)' }}>
            <div style={{ width: 38, height: 38, borderRadius: 9, background: acc.status ? 'var(--mint-tint)' : 'var(--sand-100)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <i data-lucide={acc.status ? 'check-circle' : 'alert-circle'} style={{ width: 18, height: 18, color: acc.status ? 'var(--mint)' : 'var(--amber)' }}></i>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--fg-1)', marginBottom: 4 }}>{acc.store}</div>
              <div style={{ fontSize: 12, color: 'var(--fg-3)', lineHeight: 1.5 }}>{acc.note}</div>
              {!acc.status && <window.Button size="sm" variant="secondary" style={{ marginTop: 10 }}>Set up account →</window.Button>}
            </div>
          </div>
        ))}
      </div>
    ),
    3: (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 20, alignItems: 'center', textAlign: 'center' }}>
        <div style={{ fontSize: 13, color: 'var(--fg-2)' }}>Checking your app against Apple Guideline 4.2…</div>
        <div style={{ position: 'relative', width: 140, height: 140 }}>
          <svg viewBox="0 0 140 140" style={{ width: 140, height: 140, transform: 'rotate(-90deg)' }}>
            <circle cx="70" cy="70" r="58" fill="none" stroke="var(--sand-100)" strokeWidth="8" />
            <circle cx="70" cy="70" r="58" fill="none" stroke={score >= 70 ? 'var(--mint)' : 'var(--amber)'} strokeWidth="8"
              strokeDasharray={`${(score / 100) * 364} 364`} strokeLinecap="round"
              style={{ transition: 'stroke-dasharray 80ms linear, stroke 300ms' }} />
          </svg>
          <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
            <div style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 38, lineHeight: 1, color: score >= 70 ? 'var(--mint)' : 'var(--amber)', transition: 'color 300ms' }}>{score}%</div>
            <div style={{ fontSize: 10, color: 'var(--fg-3)', marginTop: 3 }}>uniqueness</div>
          </div>
        </div>
        {score >= 70 && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '10px 18px', background: 'var(--mint-tint)', borderRadius: 999 }}>
            <i data-lucide="shield-check" style={{ width: 16, height: 16, color: 'var(--mint)' }}></i>
            <span style={{ fontSize: 13, fontWeight: 500, color: 'var(--mint-deep)' }}>Passes Apple Guideline 4.2 — ready to submit</span>
          </div>
        )}
      </div>
    ),
    4: done ? (
      <div style={{ textAlign: 'center', padding: '20px 0', display: 'flex', flexDirection: 'column', gap: 14, alignItems: 'center' }}>
        <div style={{ width: 56, height: 56, borderRadius: '50%', background: 'var(--mint-tint)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <i data-lucide="check" style={{ width: 26, height: 26, color: 'var(--mint)' }}></i>
        </div>
        <div style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 32, color: 'var(--ink)' }}>Submitted.</div>
        <div style={{ fontSize: 13, color: 'var(--fg-2)' }}>Your app is in the review queue. Apple typically approves within 1–3 days.</div>
        <window.Button onClick={onClose}>Back to publishing →</window.Button>
      </div>
    ) : (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        {[['App name', persona.appName], ['Version', '1.0.1'], ['Platforms', 'iOS + Android'], ['Uniqueness score', '78% ✓']].map(([l, v]) => (
          <div key={l} style={{ display: 'flex', justifyContent: 'space-between', padding: '10px 0', borderBottom: '1px solid var(--hairline)', fontSize: 13 }}>
            <span style={{ color: 'var(--fg-3)' }}>{l}</span>
            <span style={{ fontWeight: 500, color: 'var(--fg-1)' }}>{v}</span>
          </div>
        ))}
        <window.Button size="lg" style={{ justifyContent: 'center' }} onClick={handleSubmit} disabled={building}>
          {building ? <><window.Spinner size={14} /> Building & submitting…</> : 'Build & submit to stores →'}
        </window.Button>
      </div>
    ),
  };

  return (
    <window.Modal open={true} onClose={onClose} title="Publish update" width={500}>
      <div style={{ display: 'flex', gap: 4, marginBottom: 24 }}>
        {STEPS.map((s, i) => (
          <div key={s} style={{ flex: 1 }}>
            <div style={{ height: 3, borderRadius: 999, marginBottom: 5, background: step > i + 1 ? 'var(--mint)' : step === i + 1 ? 'var(--ink)' : 'var(--sand-100)', transition: 'background 250ms' }}></div>
            <div style={{ fontSize: 10, color: step === i + 1 ? 'var(--fg-1)' : 'var(--fg-3)', fontWeight: step === i + 1 ? 600 : 400 }}>{s}</div>
          </div>
        ))}
      </div>
      {content[step]}
      {!done && step < 4 && (
        <div style={{ display: 'flex', gap: 8, marginTop: 24, justifyContent: 'flex-end' }}>
          {step > 1 && <window.Button variant="secondary" onClick={() => setStep(s => s - 1)}>← Back</window.Button>}
          <window.Button onClick={() => setStep(s => s + 1)}>Continue →</window.Button>
        </div>
      )}
    </window.Modal>
  );
};

window.PublishingScreen = PublishingScreen;
