/* global React, DictoIcons, DictoShell */
// Steps3-4.jsx — Knowledge base + Competitor/Peer/Topic affini (Brand/Personal/Topic variants)

const {
  IconUpload, IconLink, IconFile, IconTrash, IconPlus, IconSearch,
  IconInfo, IconSparkles, IconCheck, IconX, IconChevDown, IconFolder,
} = window.DictoIcons;
const { Wizard } = window.DictoShell;

// ─── Step 03: Knowledge base ────────────────────────────────
function Step03({ tipologia = 'brand', nav = {} }) {
  const filesByType = {
    brand: [
      { ic:'pdf', name:'Nutella_Brand_Guidelines_2025.pdf', info:'4.2 MB · 28 pagine', status:'processing', pct:62 },
      { ic:'pdf', name:'Ferrero_Sustainability_Report_2024.pdf', info:'12.1 MB · 84 pagine', status:'queued' },
      { ic:'doc', name:'Messaging Framework Q2.docx', info:'320 KB · Documento interno', status:'ready' },
      { ic:'xls', name:'Category_Sales_FY24.xlsx', info:'1.8 MB · 14 sheet', status:'ready' },
      { ic:'link', name:'www.nutella.com/it — sito ufficiale', info:'Crawl profondo · 84 URL', status:'ready' },
      { ic:'link', name:'Articolo Il Sole 24 Ore — Marzo 2026', info:'Articolo singolo', status:'ready' },
    ],
    personal: [
      { ic:'pdf', name:'Intesa_Sanpaolo_Annual_Report_2024.pdf', info:'8.6 MB · 312 pagine', status:'processing', pct:48 },
      { ic:'pdf', name:'Carlo_Messina_CV_Bio.pdf', info:'420 KB · 4 pagine', status:'ready' },
      { ic:'doc', name:'Speech_Assemblea_Soci_2025.docx', info:'180 KB · Trascrizione ufficiale', status:'ready' },
      { ic:'link', name:'group.intesasanpaolo.com — sito ufficiale', info:'Crawl mirato · area governance · 42 URL', status:'ready' },
      { ic:'link', name:'Intervista Financial Times — Gennaio 2026', info:'Articolo singolo', status:'ready' },
      { ic:'link', name:'Intervista Il Sole 24 Ore — Marzo 2026', info:'Articolo singolo', status:'queued' },
    ],
    topic: [
      { ic:'pdf', name:'EU_Proposta_Regolamento_UPF_2026.pdf', info:'3.1 MB · 64 pagine', status:'processing', pct:73 },
      { ic:'pdf', name:'WHO_NOVA_Classification_Brief.pdf', info:'1.4 MB · 22 pagine', status:'ready' },
      { ic:'pdf', name:'Posizione_Industria_Dolciaria_AIDEPI.pdf', info:'2.0 MB · 18 pagine', status:'ready' },
      { ic:'xls', name:'Mercato_UPF_Italia_2020-2025.xlsx', info:'960 KB · 6 sheet', status:'ready' },
      { ic:'link', name:'efsa.europa.eu/it — area UPF', info:'Crawl mirato · 28 URL', status:'ready' },
      { ic:'link', name:'The Lancet — UPF and health (review 2025)', info:'Articolo singolo', status:'queued' },
    ],
  };
  const files = filesByType[tipologia] || filesByType.brand;

  const subjectLabel = {
    brand: 'sul brand',
    personal: 'sulla persona',
    topic: 'sul tema',
  }[tipologia];

  const statusEl = (f) => {
    if (f.status === 'ready') return <span className="file-status ready"><IconCheck size={13} stroke={3}/> Indicizzato</span>;
    if (f.status === 'queued') return <span className="file-status">In coda</span>;
    return (
      <span className="file-status">
        <span className="spinner"/>
        <span className="bar"><span style={{width: f.pct + '%'}}/></span>
        <span style={{fontVariantNumeric:'tabular-nums'}}>{f.pct}%</span>
      </span>
    );
  };

  return (
    <Wizard {...nav} step={3} done={[1,2]} title="Nuovo progetto · Knowledge base">
      <div style={{marginBottom:24, maxWidth:880}}>
        <h2 className="section-title">Contestualizza l'analisi</h2>
        <p className="section-desc">
          Aggiungi documenti, siti web o link che rappresentano la "verità" {subjectLabel}. Dicto userà questa knowledge base per confrontare ciò che dicono le AI con le fonti ufficiali e identificare gap o allucinazioni.
        </p>
      </div>

      <div className="dropzone" style={{marginBottom:20, maxWidth:1080}}>
        <div style={{display:'inline-flex', width:48, height:48, borderRadius:12, background:'#fff', border:'1px solid #EBEBEF', placeItems:'center', justifyContent:'center', marginBottom:12, color:'#4A4A52'}}>
          <IconUpload size={22}/>
        </div>
        <strong>Trascina i file qui oppure</strong>
        <div className="sub">sfoglia dal tuo computer. Accetta PDF, DOCX, XLSX, PPTX, MD, TXT — max 50 MB per file.</div>
        <div className="hstack" style={{justifyContent:'center', gap:10}}>
          <button className="btn primary"><IconUpload size={14}/> Carica file</button>
          <button className="btn secondary"><IconLink size={14}/> Aggiungi URL</button>
          <button className="btn secondary"><IconFolder size={14}/> Da Drive / SharePoint</button>
        </div>
      </div>

      <div style={{maxWidth:1080}}>
        <div className="hstack" style={{justifyContent:'space-between', marginBottom:12}}>
          <h3 style={{fontSize:14, fontWeight:600, margin:0}}>Fonti aggiunte <span className="muted" style={{fontWeight:400}}>· {files.length}</span></h3>
          <div className="hstack" style={{gap:8}}>
            <div className="input-group has-leading" style={{width:200}}>
              <span className="leading"><IconSearch size={13}/></span>
              <input className="input" style={{height:32, fontSize:12.5}} placeholder="Filtra fonti…"/>
            </div>
            <button className="btn ghost sm">Ordina per stato <IconChevDown size={12}/></button>
          </div>
        </div>

        <div>
          {files.map((f,i) => (
            <div className="file-row" key={i}>
              <div className={'file-ic ' + f.ic}>
                {f.ic === 'link' ? <IconLink size={16}/> : <IconFile size={16}/>}
              </div>
              <div className="file-meta">
                <div className="name">{f.name}</div>
                <div className="info">{f.info}</div>
              </div>
              <div className="hstack" style={{gap:14}}>
                {statusEl(f)}
                <button className="btn ghost sm" style={{padding:'0 8px', height:28}}><IconTrash size={14}/></button>
              </div>
            </div>
          ))}
        </div>

        <div style={{marginTop:20}} className="banner">
          <IconInfo size={16} className="ic"/>
          <div>
            Dicto elabora i contenuti per estrarre fatti, claim e messaggi chiave. L'elaborazione avviene in background — puoi continuare a configurare il progetto.
          </div>
        </div>
      </div>
    </Wizard>
  );
}

// ─── Step 04: Competitor / Peer / Topic affini ─────────────
function Step04({ tipologia = 'brand', nav = {} }) {
  const isPersonal = tipologia === 'personal';
  const isTopic = tipologia === 'topic';

  const brandComps = [
    { name:'Pan di Stelle Crema', owner:'Barilla', share:'Italia · 14%', seed:true, ic:'P', c:'#7A1F1F' },
    { name:'Novi Crema', owner:'Novi Elah Dufour', share:'Italia · 9%', seed:true, ic:'N', c:'#1C1C1C' },
    { name:'Nocciolata Rigoni', owner:'Rigoni di Asiago', share:'Italia · 7%', seed:true, ic:'R', c:'#2F5E2F' },
    { name:'Hershey\'s Chocolate Spread', owner:'Hershey', share:'US · 6%', seed:true, ic:'H', c:'#5B2D1A' },
  ];
  const personalPeers = [
    { name:'Andrea Orcel', owner:'CEO, UniCredit', share:'Banking IT/EU', seed:true, ic:'AO', c:'#C1272D' },
    { name:'Philippe Donnet', owner:'Group CEO, Generali', share:'Insurance IT', seed:true, ic:'PD', c:'#9B1B30' },
    { name:'Luigi Lovaglio', owner:'CEO, Monte dei Paschi', share:'Banking IT', seed:true, ic:'LL', c:'#0A4D8F' },
  ];
  const topicAffini = [
    { name:'Nutri-Score & etichettatura nutrizionale', owner:'Topic affine · Regolamentazione UE', share:'+42% YoY', seed:true, ic:'NS', c:'#1E40AF' },
    { name:'Zuccheri aggiunti e tassazione', owner:'Topic affine · Health policy', share:'+18% YoY', seed:true, ic:'ZA', c:'#9333EA' },
  ];

  const suggestedBrand = [
    { name:'Lindt Hello Spread', owner:'Lindt & Sprüngli', c:'#7B1E2B', ic:'L' },
    { name:'Milka Haselnusscreme', owner:'Mondelēz', c:'#5E3E94', ic:'M' },
    { name:'Crema Pan di Stelle Dark', owner:'Barilla', c:'#2C1810', ic:'P' },
    { name:'Biscoff Spread', owner:'Lotus Bakeries', c:'#D97706', ic:'B' },
  ];
  const suggestedPersonal = [
    { name:'Alberto Nagel', owner:'CEO, Mediobanca', c:'#0B3A7A', ic:'AN' },
    { name:'Victor Massiah', owner:'Ex CEO, UBI Banca', c:'#1F2937', ic:'VM' },
  ];
  const suggestedTopic = [
    { name:'Olio di palma e sostenibilità', owner:'Topic affine · Supply chain', c:'#15803D', ic:'OP' },
    { name:'Cibo per bambini e marketing', owner:'Topic affine · Regolamentazione', c:'#B45309', ic:'CB' },
  ];

  const seeded = isPersonal ? personalPeers : isTopic ? topicAffini : brandComps;
  const suggested = isPersonal ? suggestedPersonal : isTopic ? suggestedTopic : suggestedBrand;

  const sectionTitle = isPersonal ? 'Con chi confrontare Carlo Messina?'
    : isTopic ? 'Quali topic affini di riferimento?'
    : 'Con chi confrontare Nutella?';

  const sectionDesc = isPersonal
    ? 'Seleziona altri executive o figure pubbliche di pari grado, oltre a quelli trovati da Dicto AI. Dicto confronterà visibilità AI, narrativa e sentiment.'
    : isTopic
    ? <>Topic affini di riferimento — <span className="muted">non obbligatorio.</span> Servono per misurare la "salience" del tema rispetto a categorie limitrofe e capire dove le AI lo collocano.</>
    : 'Seleziona i competitor diretti, oltre a questi trovati da Dicto AI. Dicto confronterà la narrativa AI — share of voice, sentiment, attributi associati — tra Nutella e questi brand.';

  const cardTitle = isPersonal ? 'Peer selezionati' : isTopic ? 'Topic affini selezionati' : 'Competitor selezionati';
  const stepLabel = isPersonal ? 'Peer' : isTopic ? 'Topic affini' : 'Competitor';

  return (
    <Wizard {...nav} step={4} done={[1,2,3]} title={'Nuovo progetto · ' + stepLabel}>

      <div style={{marginBottom:24, maxWidth:880}}>
        <h2 className="section-title">{sectionTitle}</h2>
        <p className="section-desc">{sectionDesc}</p>
      </div>

      <div className="banner brand" style={{marginBottom:20, maxWidth:1080}}>
        <IconSparkles size={16} className="ic"/>
        <div>
          <strong>Dicto AI ha identificato {seeded.length} {isPersonal ? 'peer' : isTopic ? 'topic affini' : 'competitor diretti'}.</strong>{' '}
          Conferma quelli rilevanti, elimina i non pertinenti o aggiungine altri.
        </div>
      </div>

      <div className="card" style={{marginBottom:16, maxWidth:1080}}>
        <div className="card-head">
          <h3 className="card-title">{cardTitle} <span style={{color:'#8A8A93', fontWeight:500}}>· {seeded.length}</span></h3>
          <p className="card-desc">
            {isPersonal ? 'Inclusi in ogni analisi comparativa.'
            : isTopic ? 'Usati come riferimento per misurare la rilevanza relativa del tema.'
            : 'Inclusi in ogni analisi comparativa.'}
          </p>
        </div>
        <div style={{padding:'8px 16px 16px'}}>
          {seeded.map((c,i) => (
            <div className="file-row" key={i} style={{border:'1px solid #EBEBEF', marginTop: i>0 ? 8 : 0}}>
              <div className="file-ic" style={{background:c.c, color:'#fff', fontWeight:700, fontSize:c.ic.length>1?11:13}}>{c.ic}</div>
              <div className="file-meta">
                <div className="name">{c.name}</div>
                <div className="info">{c.owner}{c.share ? ' · ' + c.share : ''}</div>
              </div>
              <div className="hstack" style={{gap:10}}>
                {c.seed && <span className="chip" style={{height:22, fontSize:11, background:'#F1EBFF', color:'#6D28D9', borderColor:'transparent'}}><IconSparkles size={10}/> Auto · da confermare</span>}
                <button className="btn ghost sm" style={{padding:'0 8px', height:28}}><IconX size={14}/></button>
              </div>
            </div>
          ))}
        </div>
      </div>

      <div style={{marginBottom:12, maxWidth:1080}}>
        <div className="hstack" style={{justifyContent:'space-between', marginBottom:10}}>
          <h3 style={{fontSize:14, fontWeight:600, margin:0}}>
            {isPersonal ? 'Aggiungi altri peer' : isTopic ? 'Aggiungi un topic affine' : 'Aggiungi altri competitor'}
          </h3>
          <span className="muted" style={{fontSize:12}}>Massimo 8 per progetto</span>
        </div>
        <div className="input-group has-leading">
          <span className="leading"><IconSearch size={15}/></span>
          <input className="input" placeholder={isPersonal ? 'Cerca per nome o azienda…' : isTopic ? 'Cerca un topic, una categoria…' : 'Cerca per nome brand, dominio o azienda…'} />
        </div>

        {suggested.length > 0 && <>
          <div style={{fontSize:11.5, fontWeight:600, color:'#8A8A93', textTransform:'uppercase', letterSpacing:'0.06em', margin:'16px 0 8px'}}>Suggeriti per te</div>
          <div className="grid-2">
            {suggested.map((c,i) => (
              <div key={i} style={{display:'flex', gap:12, padding:'12px 14px', border:'1px solid #EBEBEF', borderRadius:10, background:'#fff', alignItems:'center'}}>
                <div className="file-ic" style={{background:c.c, color:'#fff', fontWeight:700, fontSize:c.ic.length>1?11:13}}>{c.ic}</div>
                <div style={{flex:1, minWidth:0}}>
                  <div style={{fontSize:13, fontWeight:500, color:'#0A0A0B'}}>{c.name}</div>
                  <div style={{fontSize:11.5, color:'#8A8A93'}}>{c.owner}</div>
                </div>
                <button className="btn secondary sm"><IconPlus size={12}/> Aggiungi</button>
              </div>
            ))}
          </div>
        </>}
      </div>
    </Wizard>
  );
}

window.DictoSteps34 = { Step03, Step04 };
