// Prodz — Production import (brief §1.4 + Roberto): "Crea → Produzione" opens a
// dedicated screen. Three entry methods converge on one metadata form:
//   · Link Instagram   — incolla il link, anteprima media, campi compilati da un
//                        modello AI (titolo, brand, categoria, prodotto da, credits).
//   · Chrome extension — installi il plugin, apri un post IG, clicchi "Importa".
//   · Caricamento manuale — gli stessi campi, compilati a mano.
// Poi una revisione di crew e credits → la produzione è importata.

const PROD_CATEGORIES = [
  { it: 'Editoriale moda', en: 'Fashion editorial' },
  { it: 'Commercial', en: 'Commercial' },
  { it: 'Video musicale', en: 'Music video' },
  { it: 'Documentario', en: 'Documentary' },
  { it: 'Cortometraggio', en: 'Short film' },
  { it: 'Architettura', en: 'Architecture' },
];

function ImportProduction() {
  const { L } = useL();
  const nav = useNav();
  const { Button, Avatar } = window.ProdzDesignSystem_d0b87b;

  const [step, setStep] = useStateS('method');     // method | instagram | extension | analyzing | form | review
  const [method, setMethod] = useStateS(null);
  const [link, setLink] = useStateS('');

  // metadata
  const [media, setMedia] = useStateS([]);
  const [title, setTitle] = useStateS('');
  const [brand, setBrand] = useStateS('');
  const [category, setCategory] = useStateS('');
  const [producedBy, setProducedBy] = useStateS('');
  const [credits, setCredits] = useStateS([]);
  const [ai, setAi] = useStateS(false);
  const [picking, setPicking] = useStateS(false);

  // Simulate an AI pass over the Instagram post → auto-fill everything.
  const runAI = () => {
    setStep('analyzing');
    setTimeout(() => {
      setMedia([IMG.fashion, IMG.av1, IMG.interior]);
      setTitle('Collezione Aurora');
      setBrand('Maison Vela');
      setCategory(tr(L, PROD_CATEGORIES[0]));
      setProducedBy('Studio Lumen');
      setCredits([
        { id: 'sofia', role: tr(L, PEOPLE.sofia.role) },
        { id: 'elena', role: tr(L, PEOPLE.elena.role) },
        { id: 'nina', role: tr(L, PEOPLE.nina.role) },
      ]);
      setAi(true);
      setStep('form');
    }, 1600);
  };

  const startManual = () => {
    setMethod('manual'); setMedia([]); setAi(false);
    setCredits([{ id: 'me', role: tr(L, PEOPLE.me.role) }]);
    setStep('form');
  };

  const back = () => {
    if (step === 'method') return nav.pop();
    if (step === 'instagram' || step === 'extension') return setStep('method');
    if (step === 'form') return setStep(method === 'manual' ? 'method' : method);
    if (step === 'review') return setStep('form');
    return nav.pop();
  };

  const setRole = (id, role) => setCredits((cs) => cs.map((c) => c.id === id ? { ...c, role } : c));
  const removeCredit = (id) => setCredits((cs) => cs.filter((c) => c.id !== id));
  const addCredit = (id) => { setCredits((cs) => [...cs, { id, role: tr(L, PEOPLE[id].role) }]); setPicking(false); };
  const available = Object.keys(PEOPLE).filter((id) => !credits.some((c) => c.id === id));

  const finishImport = () => {
    nav.pop();
    nav.toast(L('Produzione importata · ora è nel tuo profilo', 'Production imported · now on your profile'), null);
  };

  const headerTitle = L('Importa produzione', 'Import production');

  return (
    <div className="pz-screen-enter" style={{ display: 'flex', flexDirection: 'column', minHeight: '100%' }}>
      <TopBar title={headerTitle} onBack={back} showLang={false} />

      {/* progress dots — once you're past the method chooser */}
      {step !== 'method' && (
        <div style={{ display: 'flex', gap: 6, padding: '14px 16px 0' }}>
          {['source', 'form', 'review'].map((s, i) => {
            const reached = (step === 'review' ? 2 : step === 'form' ? 1 : 0) >= i;
            return <span key={s} style={{ flex: 1, height: 4, borderRadius: 2, background: reached ? 'var(--prodz-teal)' : 'var(--ink-700)' }} />;
          })}
        </div>
      )}

      {/* ───────── METHOD CHOOSER ───────── */}
      {step === 'method' && (
        <div style={{ padding: '18px 16px 28px' }}>
          <h1 style={pageTitle}>{L('Come vuoi importare?', 'How do you want to import?')}</h1>
          <p style={pageSub}>{L('Porta un progetto su Prodz: genereremo Moments e Thread collegati.', 'Bring a project onto Prodz — we’ll create linked Moments & Threads.')}</p>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 18 }}>
            <OptionCard icon="AtSign" tint="var(--prodz-gold)"
              title={L('Da link Instagram', 'From Instagram link')}
              sub={L('Incolla il link: l’AI compila titolo, brand, categoria e credits.', 'Paste a link — AI fills title, brand, category & credits.')}
              onClick={() => { setMethod('instagram'); setStep('instagram'); }} />
            <OptionCard icon="Puzzle" tint="var(--prodz-teal)"
              title={L('Chrome extension', 'Chrome extension')}
              sub={L('Dal post Instagram, clicca “Importa su Prodz”.', 'From an Instagram post, click “Import to Prodz”.')}
              onClick={() => { setMethod('extension'); setStep('extension'); }} />
            <OptionCard icon="Upload" tint="var(--blue)"
              title={L('Caricamento manuale', 'Manual upload')}
              sub={L('Carica i media e compila i campi a mano.', 'Upload media and fill the fields yourself.')}
              onClick={startManual} />
          </div>
        </div>
      )}

      {/* ───────── INSTAGRAM LINK ───────── */}
      {step === 'instagram' && (
        <div style={{ padding: '20px 16px 28px' }}>
          <SheetHead icon="AtSign" tint="var(--prodz-gold)" eyebrow={L('Da link Instagram', 'From Instagram link')} title={L('Incolla il link del post', 'Paste the post link')} onBack={() => setStep('method')} L={L} />
          <IField label={L('Link del post o reel', 'Post or reel link')}>
            <input value={link} onChange={(e) => setLink(e.target.value)} placeholder="instagram.com/p/…" style={impInput} />
          </IField>
          <div style={impNote}>
            <Ic n="Sparkles" s={15} color="var(--prodz-teal)" />
            <span>{L('Un modello AI leggerà il post e precompilerà titolo, brand, categoria, chi l’ha prodotto e i credits. Potrai rivedere tutto.', 'An AI model reads the post and pre-fills title, brand, category, producer and credits. You can review everything.')}</span>
          </div>
          <div style={{ marginTop: 18 }}>
            <Button variant="primary" glow fullWidth leadingIcon={<Ic n="Sparkles" s={16} />} onClick={runAI}>{L('Analizza con l’AI', 'Analyze with AI')}</Button>
          </div>
        </div>
      )}

      {/* ───────── CHROME EXTENSION ───────── */}
      {step === 'extension' && (
        <div style={{ padding: '20px 16px 28px' }}>
          <SheetHead icon="Puzzle" tint="var(--prodz-teal)" eyebrow={L('Chrome extension', 'Chrome extension')} title={L('Importa da un post aperto', 'Import from an open post')} onBack={() => setStep('method')} L={L} />
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            <ExtStep n="1" icon="Download" text={L('Installa il plugin Prodz per Chrome.', 'Install the Prodz Chrome plugin.')} L={L} />
            <ExtStep n="2" icon="AtSign" text={L('Apri un post o reel su Instagram.', 'Open a post or reel on Instagram.')} L={L} />
            <ExtStep n="3" icon="MousePointerClick" text={L('Clicca “Importa su Prodz”: i media e i campi arrivano qui.', 'Click “Import to Prodz” — media & fields land here.')} L={L} />
          </div>
          <div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
            <Button variant="secondary" fullWidth leadingIcon={<Ic n="Globe" s={16} />} onClick={() => nav.toast(L('Apertura Chrome Web Store…', 'Opening Chrome Web Store…'), null)}>{L('Installa', 'Install')}</Button>
            <Button variant="primary" glow fullWidth leadingIcon={<Ic n="Sparkles" s={16} />} onClick={runAI}>{L('Simula importazione', 'Simulate import')}</Button>
          </div>
        </div>
      )}

      {/* ───────── ANALYZING ───────── */}
      {step === 'analyzing' && (
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 18, padding: 40 }}>
          <span style={{ position: 'relative', width: 58, height: 58 }}>
            <span style={{ position: 'absolute', inset: 0, borderRadius: '50%', border: '3px solid var(--ink-700)', borderTopColor: 'var(--prodz-teal)', animation: 'pz-spin 0.8s linear infinite' }} />
            <span style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Ic n="Sparkles" s={22} color="var(--prodz-teal)" /></span>
          </span>
          <div style={{ textAlign: 'center' }}>
            <div style={{ fontSize: 15.5, fontWeight: 700, color: 'var(--text-primary)' }}>{L('Analisi del post con l’AI…', 'Analyzing the post with AI…')}</div>
            <div style={{ fontSize: 12.5, color: 'var(--text-muted)', marginTop: 5 }}>{L('Leggo media, titolo, brand e i credits.', 'Reading media, title, brand and credits.')}</div>
          </div>
        </div>
      )}

      {/* ───────── FORM ───────── */}
      {step === 'form' && (
        <div style={{ padding: '16px 16px 28px' }}>
          {ai && (
            <div style={{ ...impNote, background: 'var(--teal-surface)', boxShadow: 'var(--ring-teal)', color: 'var(--prodz-teal)', marginBottom: 16 }}>
              <Ic n="Sparkles" s={15} color="var(--prodz-teal)" />
              <span style={{ color: 'var(--text-body)' }}>{L('Campi precompilati dall’AI. Controlla e modifica quello che serve.', 'Fields pre-filled by AI. Review and edit anything you need.')}</span>
            </div>
          )}

          {/* media preview / upload */}
          <IField label={L('Media', 'Media')} ai={ai && media.length > 0} L={L}>
            {media.length > 0 ? (
              <div className="hscroll" style={{ gap: 10 }}>
                {media.map((src, i) => (
                  <div key={i} style={{ width: 132, height: 168, flexShrink: 0, borderRadius: 14, background: `#111 url(${src}) center/cover`, boxShadow: 'var(--ring-inset-hairline)', scrollSnapAlign: 'start' }} />
                ))}
                <button onClick={() => nav.toast(L('Aggiungi media', 'Add media'), null)} style={uploadSlot} aria-label={L('Aggiungi', 'Add')}>
                  <Ic n="Plus" s={22} color="var(--text-muted)" />
                </button>
              </div>
            ) : (
              <button onClick={() => nav.toast(L('Apertura caricamento…', 'Opening upload…'), null)} style={{ ...uploadSlot, width: '100%', height: 150, flexDirection: 'column', gap: 8 }}>
                <Ic n="ImagePlus" s={26} color="var(--text-muted)" />
                <span style={{ fontSize: 12.5, color: 'var(--text-muted)', fontWeight: 600 }}>{L('Carica foto e video del progetto', 'Upload project photos & videos')}</span>
              </button>
            )}
          </IField>

          <IField label={L('Titolo', 'Title')} ai={ai} L={L}>
            <input value={title} onChange={(e) => setTitle(e.target.value)} placeholder={L('Nome della produzione…', 'Production name…')} style={impInput} />
          </IField>

          <IField label={L('Brand', 'Brand')} ai={ai} L={L}>
            <input value={brand} onChange={(e) => setBrand(e.target.value)} placeholder={L('es. Maison Vela', 'e.g. Maison Vela')} style={impInput} />
          </IField>

          <IField label={L('Categoria', 'Category')} ai={ai} L={L}>
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              {PROD_CATEGORIES.map((c) => {
                const v = tr(L, c); const on = category === v;
                return <button key={v} onClick={() => setCategory(v)} style={chipStyle(on)}>{v}</button>;
              })}
            </div>
          </IField>

          <IField label={L('Prodotto da', 'Produced by')} ai={ai} L={L}>
            <input value={producedBy} onChange={(e) => setProducedBy(e.target.value)} placeholder={L('Casa di produzione o persona…', 'Production house or person…')} style={impInput} />
          </IField>

          {/* credits */}
          <IField label={L('Credits & crew', 'Credits & crew')} ai={ai && credits.length > 0} L={L}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {credits.map((c) => {
                const p = PEOPLE[c.id]; if (!p) return null;
                const roleOpts = ROLES.map((r) => tr(L, r));
                if (!roleOpts.includes(c.role)) roleOpts.unshift(c.role);
                return (
                  <div key={c.id} style={creditRow}>
                    <Avatar src={p.avatar} alt={p.name} size={36} ring={p.ring} />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 13.5, fontWeight: 700, color: 'var(--text-primary)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{p.name}{c.id === 'me' && L(' · Tu', ' · You')}</div>
                      <select value={c.role} onChange={(e) => setRole(c.id, e.target.value)} style={impSelect}>
                        {roleOpts.map((r) => <option key={r} value={r}>{r}</option>)}
                      </select>
                    </div>
                    <button onClick={() => removeCredit(c.id)} aria-label={L('Rimuovi', 'Remove')} style={iconGhostBtn}><Ic n="X" s={16} color="var(--text-subtle)" /></button>
                  </div>
                );
              })}

              {picking ? (
                <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', padding: '4px 2px' }}>
                  {available.length === 0 && <span style={{ fontSize: 12.5, color: 'var(--text-subtle)' }}>{L('Tutti aggiunti.', 'Everyone added.')}</span>}
                  {available.map((id) => {
                    const p = PEOPLE[id];
                    return (
                      <button key={id} onClick={() => addCredit(id)} style={{ display: 'flex', alignItems: 'center', gap: 7, padding: '5px 11px 5px 5px', border: 'none', cursor: 'pointer', borderRadius: 'var(--radius-pill)', background: 'var(--surface-raised)', boxShadow: 'var(--ring-inset-hairline)' }}>
                        <Avatar src={p.avatar} alt={p.name} size={24} ring={p.ring} />
                        <span style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--text-body)' }}>{p.name.split(' ')[0]}</span>
                      </button>
                    );
                  })}
                </div>
              ) : (
                <button onClick={() => setPicking(true)} style={addCreditBtn}>
                  <Ic n="UserPlus" s={16} color="var(--prodz-teal)" />{L('Aggiungi credit', 'Add credit')}
                </button>
              )}
            </div>
          </IField>

          <div style={{ marginTop: 18 }}>
            <Button variant="primary" glow fullWidth leadingIcon={<Ic n="ArrowRight" s={16} />} onClick={() => setStep('review')}>{L('Rivedi crew e credits', 'Review crew & credits')}</Button>
          </div>
        </div>
      )}

      {/* ───────── REVIEW ───────── */}
      {step === 'review' && (
        <div style={{ padding: '16px 16px 28px' }}>
          <h1 style={pageTitle}>{L('Revisione crew & credits', 'Review crew & credits')}</h1>
          <p style={pageSub}>{L('Conferma chi ha collaborato e i ruoli, poi importa.', 'Confirm who collaborated and their roles, then import.')}</p>

          {/* summary card */}
          <div style={{ display: 'flex', gap: 12, marginTop: 16, padding: 12, background: 'var(--surface-card)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--ring-inset-hairline)' }}>
            <div style={{ width: 64, height: 80, flexShrink: 0, borderRadius: 12, background: media[0] ? `#111 url(${media[0]}) center/cover` : 'var(--surface-raised)', display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: 'var(--ring-inset-hairline)' }}>
              {!media[0] && <Ic n="Clapperboard" s={22} color="var(--text-muted)" />}
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 16, fontWeight: 800, color: 'var(--text-primary)', letterSpacing: '-0.01em' }}>{title || L('Senza titolo', 'Untitled')}</div>
              <div style={{ fontSize: 12.5, color: 'var(--text-muted)', marginTop: 3 }}>{[brand, category].filter(Boolean).join(' · ') || '—'}</div>
              {producedBy && <div style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11.5, color: 'var(--text-subtle)', marginTop: 6 }}><Ic n="Building2" s={12} color="var(--text-subtle)" />{L('Prodotto da', 'Produced by')} {producedBy}</div>}
            </div>
          </div>

          <Eyebrow style={{ margin: '20px 2px 10px' }}>{credits.length} {L('credits', 'credits')}</Eyebrow>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {credits.map((c) => {
              const p = PEOPLE[c.id]; if (!p) return null;
              return (
                <div key={c.id} style={{ ...creditRow, cursor: 'default' }}>
                  <Avatar src={p.avatar} alt={p.name} size={38} ring={p.ring} status={p.online ? 'online' : null} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--text-primary)' }}>{p.name}{c.id === 'me' && L(' · Tu', ' · You')}</div>
                    <div style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 1 }}>{c.role}</div>
                  </div>
                  <Ic n="CircleCheck" s={20} color="var(--prodz-teal)" />
                </div>
              );
            })}
          </div>

          <div style={{ display: 'flex', gap: 8, marginTop: 20 }}>
            <Button variant="secondary" leadingIcon={<Ic n="ChevronLeft" s={16} />} onClick={() => setStep('form')}>{L('Indietro', 'Back')}</Button>
            <Button variant="primary" glow fullWidth leadingIcon={<Ic n="Check" s={16} />} onClick={finishImport}>{L('Importa produzione', 'Import production')}</Button>
          </div>
        </div>
      )}
    </div>
  );
}

function ExtStep({ n, icon, text, L }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: 13, background: 'var(--surface-card)', borderRadius: 'var(--radius-md)', boxShadow: 'var(--ring-inset-hairline)' }}>
      <span style={{ width: 30, height: 30, flexShrink: 0, borderRadius: '50%', background: 'var(--teal-surface)', boxShadow: 'var(--ring-teal)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 13, fontWeight: 800, color: 'var(--prodz-teal)' }}>{n}</span>
      <Ic n={icon} s={18} color="var(--text-muted)" />
      <span style={{ flex: 1, fontSize: 13.5, color: 'var(--text-body)', lineHeight: 1.4 }}>{text}</span>
    </div>
  );
}

function IField({ label, ai, L, children, style }) {
  return (
    <div style={{ marginBottom: 14, ...style }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 7, margin: '0 0 8px' }}>
        <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--text-subtle)' }}>{label}</span>
        {ai && (
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, padding: '2px 7px', borderRadius: 'var(--radius-pill)', background: 'var(--teal-surface)', boxShadow: 'var(--ring-teal)', fontSize: 9, fontWeight: 800, letterSpacing: '0.04em', color: 'var(--prodz-teal)' }}>
            <Ic n="Sparkles" s={10} color="var(--prodz-teal)" />AI
          </span>
        )}
      </div>
      {children}
    </div>
  );
}

const chipStyle = (on) => ({
  height: 36, padding: '0 14px', borderRadius: 'var(--radius-pill)', border: 'none', cursor: 'pointer',
  fontSize: 12.5, fontWeight: 700, whiteSpace: 'nowrap',
  background: on ? 'var(--teal-surface)' : 'var(--surface-raised)',
  color: on ? 'var(--prodz-teal)' : 'var(--text-muted)',
  boxShadow: on ? 'var(--ring-teal)' : 'var(--ring-inset-hairline)',
});

const impInput = { width: '100%', height: 46, padding: '0 14px', borderRadius: 'var(--radius-md)', border: 'none', outline: 'none', background: 'var(--surface-raised)', boxShadow: 'var(--ring-inset-hairline)', color: 'var(--text-body)', fontSize: 15, fontFamily: 'var(--font-ui)' };
const impSelect = { marginTop: 3, height: 30, padding: '0 8px', borderRadius: 8, border: 'none', outline: 'none', background: 'var(--surface-canvas)', boxShadow: 'var(--ring-inset-hairline)', color: 'var(--text-muted)', fontSize: 12.5, fontWeight: 600, fontFamily: 'var(--font-ui)', maxWidth: '100%' };
const impNote = { display: 'flex', alignItems: 'flex-start', gap: 9, padding: '12px 14px', borderRadius: 'var(--radius-md)', background: 'var(--surface-card)', boxShadow: 'var(--ring-inset-hairline)', fontSize: 12.5, lineHeight: 1.45, color: 'var(--text-muted)' };
const creditRow = { display: 'flex', alignItems: 'center', gap: 11, padding: 10, background: 'var(--surface-card)', borderRadius: 'var(--radius-md)', boxShadow: 'var(--ring-inset-hairline)' };
const iconGhostBtn = { width: 30, height: 30, flexShrink: 0, borderRadius: '50%', border: 'none', cursor: 'pointer', background: 'var(--surface-raised)', display: 'flex', alignItems: 'center', justifyContent: 'center' };
const uploadSlot = { width: 96, height: 168, flexShrink: 0, borderRadius: 14, border: '1.5px dashed var(--hairline-strong)', background: 'var(--surface-raised)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', scrollSnapAlign: 'start' };
const addCreditBtn = { display: 'inline-flex', alignItems: 'center', gap: 8, alignSelf: 'flex-start', height: 40, padding: '0 16px', borderRadius: 'var(--radius-pill)', border: '1.5px dashed var(--hairline-strong)', background: 'none', cursor: 'pointer', fontSize: 13, fontWeight: 700, color: 'var(--prodz-teal)', marginTop: 2 };

Object.assign(window, { ImportProduction, PROD_CATEGORIES });
