// ---------- Software detail page ----------

// Parse price string → monthly euros (best effort)
function parsePriceMonthly(priceStr) {
  if (!priceStr) return null;
  // Find all euro/dollar figures with /mese or /utente/mese context
  const matches = [...priceStr.matchAll(/([€$])\s*([\d.,]+)\s*(?:\/utente)?\s*\/\s*(mese|month|anno|year)/gi)];
  if (!matches.length) return null;
  let best = null;
  for (const m of matches) {
    const currency = m[1];
    let amt = parseFloat(m[2].replace(',', '.'));
    if (isNaN(amt)) continue;
    // Convert $ to € at rough parity (0.92) — close enough for "starting from" display
    if (currency === '$') amt = amt * 0.92;
    // Convert yearly → monthly
    const period = m[3].toLowerCase();
    if (period.startsWith('ann') || period.startsWith('year')) amt = amt / 12;
    if (best === null || amt < best) best = amt;
  }
  return best;
}

function formatEur(n, decimals=0) {
  if (n === null || n === undefined || isNaN(n)) return null;
  return new Intl.NumberFormat('it-IT', { minimumFractionDigits: decimals, maximumFractionDigits: decimals }).format(Math.round(n * (decimals>0?100:1)) / (decimals>0?100:1));
}

function SoftwarePage({ sw, onNav, allData = [] }) {
  React.useEffect(() => {
    const title = sw.seo?.title || `Alternative gratis a ${sw.nome} (2026) — Le migliori testate`;
    const description = sw.seo?.meta_description || `Cerchi un'alternativa gratuita a ${sw.nome}? Ecco le migliori alternative gratis e open source a ${sw.nome}, testate e confrontate.`;
    const keywords = [sw.seo?.keyword_primaria, ...(sw.seo?.keyword_secondarie||[]), `alternativa gratis a ${sw.nome}`, `${sw.nome} alternativa gratuita`].filter(Boolean).join(', ');

    applyPageSEO({
      title,
      description,
      path: `/alternativa/${sw.slug}`,
      type: 'article',
      keywords,
    });

    injectSoftwareSchema(sw);
    window.scrollTo({top:0, behavior:'instant'});
  }, [sw.id]);

  const alts = React.useMemo(() => [...sw.alternative].sort((a,b)=>b.valutazione-a.valutazione), [sw]);
  const faqs = buildFaqs(sw, alts);
  const best = alts[0];
  const openCount = alts.filter(a => a.open_source).length;
  const monthly = parsePriceMonthly(sw.prezzo);
  const yearly = monthly ? monthly * 12 : null;
  const h1 = sw.seo?.h1 || `Le migliori alternative gratuite a ${sw.nome}`;
  const keywordPrimaria = sw.seo?.keyword_primaria || `alternativa gratis a ${sw.nome}`;

  // Related software: same category, excluding current. Up to 6.
  const related = React.useMemo(() => {
    if (!Array.isArray(allData) || !allData.length) return [];
    return allData
      .filter(s => s.id !== sw.id && s.categoria === sw.categoria)
      .sort((a, b) => (b.alternative.length - a.alternative.length) || a.nome.localeCompare(b.nome))
      .slice(0, 6);
  }, [allData, sw.id]);

  // Quick punto-di-forza extraction: first 2 perks split on comma
  const bestPerks = (best.punti_forza || '').split(/,\s*/).slice(0, 3).map(s => s.trim()).filter(Boolean);

  return (
    <div className="view">
      <div className="container-narrow">
        <nav className="breadcrumbs" aria-label="breadcrumb">
          <a href="#/" onClick={(e)=>{e.preventDefault(); onNav('/');}}>Home</a>
          <span className="sep">/</span>
          <a href={`#/categoria/${slugify(sw.categoria)}`} onClick={(e)=>{e.preventDefault(); onNav(`/categoria/${slugify(sw.categoria)}`);}}>{sw.categoria}</a>
          <span className="sep">/</span>
          <span>{sw.nome}</span>
        </nav>

        <div className="sw-hero" style={{paddingBottom: 12}}>
          <div className="sw-eyebrow">Smetti di pagare {sw.nome}. Passa a {best.nome}, gratis.</div>
          <h1>{renderH1(h1, sw.nome)}</h1>
          <p className="sub">
            Stai cercando un'<strong>{keywordPrimaria}</strong>? In questa pagina trovi le {alts.length} migliori alternative gratuite e open source a {sw.nome}, testate personalmente e confrontate. {monthly ? <>Risparmia fino a <strong style={{color:'#15803d'}}>€{formatEur(yearly, 0)}/anno</strong> passando a {best.nome}.</> : <>Tutte completamente gratis, senza limiti nascosti.</>} {openCount > 0 && <>{openCount} sono open source · </>}aggiornato {new Date().toLocaleDateString('it-IT', {month:'long', year:'numeric'})}.
          </p>
        </div>

        {/* ABOVE-THE-FOLD COMPARISON */}
        <div className="vs-hero">
          <div className="vs-hero-top">
            <span className="vs-tag">✦ Alternativa consigliata</span>
            {monthly && <span className="vs-updated">Basato sul prezzo attuale di {sw.nome}</span>}
          </div>
          <div className="vs-grid">
            <div className="vs-card paid">
              <span className="vs-card-label">Quello che paghi oggi</span>
              <div className="vs-card-head">
                <Logo name={sw.nome} size={44} url={sw.sito_ufficiale} />
                <h3>{sw.nome}</h3>
              </div>
              <div className="vs-price">
                {monthly ? <>€{formatEur(monthly, 0)}<small>/mese</small></> : <>{sw.prezzo.split('/')[0]}</>}
              </div>
              <div className="vs-perks">
                <span className="perk bad">✕ {truncate(sw.perche_cercano_alternativa, 90)}</span>
              </div>
            </div>

            <div className="vs-arrow-cell">
              {monthly && <div className="vs-save"><span className="amt">-€{formatEur(yearly, 0)}</span><span className="period">all'anno</span></div>}
              <svg className="vs-arrow-svg" width="48" height="32" viewBox="0 0 48 32" fill="none"><path d="M4 16 L40 16 M32 6 L44 16 L32 26" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"/></svg>
            </div>

            <div className="vs-mobile-arrow">
              {monthly && <div className="vs-save"><span className="amt">-€{formatEur(yearly, 0)}</span><span className="period">all'anno</span></div>}
            </div>

            <div className="vs-card free">
              <span className="vs-card-label">✓ La tua nuova scelta — Gratis</span>
              <div className="vs-card-head">
                <Logo name={best.nome} size={44} url={best.sito_ufficiale} />
                <h3>{best.nome}</h3>
              </div>
              <div className="vs-price">€0<small>/per sempre</small></div>
              <div className="vs-perks">
                {bestPerks.slice(0, 3).map((p, i) => <span key={i} className="perk good">✓ {p}</span>)}
              </div>
              <a className="btn btn-primary cta" href={best.sito_ufficiale} target="_blank" rel="noopener noreferrer">
                Inizia gratis con {best.nome} <Icon.arrow />
              </a>
            </div>
          </div>

          {/* 3-cell synthesis: perché, per chi, risparmio */}
          <div className="vs-summary">
            <div className="vs-summary-cell">
              <h4>✦ Cosa fa</h4>
              <p>{truncate(best.descrizione_it, 110)}</p>
            </div>
            <div className="vs-summary-cell">
              <h4>◆ Ideale per</h4>
              <p><strong>{best.ideale_per}</strong></p>
            </div>
            <div className="vs-summary-cell">
              <h4>● Perché conviene</h4>
              <p>{best.open_source ? 'Open source, trasparente e senza vendor lock-in.' : 'Piano gratuito completo, senza limiti nascosti.'} {monthly ? <>Risparmi <strong>€{formatEur(yearly, 0)}/anno</strong>.</> : ''}</p>
            </div>
          </div>
        </div>

        {/* Context panel (about the paid software) */}
        <details style={{background:'var(--surface)', border:'1px solid var(--border)', borderRadius:12, padding:'14px 18px', marginBottom: 24}}>
          <summary style={{cursor:'pointer', fontSize:14, fontWeight:500, color:'var(--ink-2)', listStyle:'none', display:'flex', alignItems:'center', gap:8}}>
            <span style={{color:'var(--ink-3)'}}>▸</span>
            Maggiori informazioni su {sw.nome}
          </summary>
          <div style={{marginTop:14, display:'grid', gridTemplateColumns:'auto 1fr', gap:16, alignItems:'start'}}>
            <Logo name={sw.nome} size={48} url={sw.sito_ufficiale} />
            <div>
              <div style={{fontSize:14, color:'var(--ink-3)', marginBottom:6}}><strong style={{color:'var(--ink-2)'}}>{sw.sviluppatore}</strong> · {sw.categoria}</div>
              <p style={{margin:'0 0 8px', color:'var(--ink-2)', fontSize:14.5, lineHeight:1.55}}>{sw.descrizione_it}</p>
              <div style={{fontSize:13.5, color:'var(--ink-3)'}}>
                <strong style={{color:'var(--ink-2)'}}>Prezzo:</strong> {sw.prezzo} · <strong style={{color:'var(--ink-2)'}}>Piattaforme:</strong> {sw.piattaforme.join(', ')}
              </div>
            </div>
          </div>
        </details>

        <section style={{padding:'8px 0'}}>
          <div className="section-header" style={{marginBottom:12}}>
            <h2>Tutte le {alts.length} alternative gratuite a {sw.nome}</h2>
          </div>
          <p style={{color:'var(--ink-2)', fontSize:16, lineHeight:1.6, margin:'0 0 24px', maxWidth:680}}>
            Ordinate per qualità complessiva. Ognuna è stata testata personalmente — ecco cosa funziona davvero e cosa no.
          </p>
          <div className="alt-list">
            {alts.map((alt, i) => <AlternativeCard key={alt.id+i} alt={alt} rank={i+1} featured={i===0} paidMonthly={monthly} />)}
          </div>
        </section>

        <section style={{padding:'32px 0 8px'}}>
          <div className="section-header" style={{marginBottom:16}}><h2>Confronto rapido</h2></div>
          <CompareTable alts={alts} paid={sw} paidMonthly={monthly} />
        </section>

        <section style={{padding:'32px 0 8px'}}>
          <div className="section-header" style={{marginBottom:16}}><h2>Come scegliere l'alternativa giusta a {sw.nome}</h2></div>
          <div className="editorial">
            <p>Cambiare software sembra difficile, ma nella maggior parte dei casi sono 10 minuti di setup e zero compromessi. Ecco i 5 criteri che contano davvero:</p>
            <ul>
              <li><strong>Piattaforme.</strong> Funziona su tutti i dispositivi che usi — desktop, web, mobile. Se usi {sw.piattaforme.slice(0,3).join(', ')}, scegli un'alternativa che li copra tutti.</li>
              <li><strong>Privacy e controllo.</strong> Le soluzioni open source e self-hostabili ti danno il controllo totale dei dati; i servizi cloud sono più comodi ma meno trasparenti.</li>
              <li><strong>Piano gratuito davvero gratuito.</strong> Alcune alternative sono 100% free; altre sono freemium con limiti che potrebbero bloccarti. Controlla bene prima.</li>
              <li><strong>Migrazione facile.</strong> Se usi già {sw.nome}, verifica che l'alternativa importi i tuoi file o progetti esistenti.</li>
              <li><strong>Community attiva.</strong> I progetti con community forti ricevono aggiornamenti frequenti e bug fix rapidi.</li>
            </ul>
          </div>
        </section>

        <section style={{padding:'32px 0 8px'}}>
          <div className="section-header" style={{marginBottom:16}}><h2>Domande frequenti su {sw.nome}</h2></div>
          <div className="faq-list">
            {faqs.map((f, i) => (
              <details key={i} className="faq">
                <summary>{f.q}</summary>
                <p>{f.a}</p>
              </details>
            ))}
          </div>
        </section>

        {related.length > 0 && (
          <section style={{padding:'32px 0 8px'}}>
            <div className="section-header" style={{marginBottom:6}}>
              <h2>Software correlati in {sw.categoria}</h2>
            </div>
            <p style={{color:'var(--ink-3)', fontSize:14.5, margin:'0 0 18px', maxWidth:620}}>
              Altri software della stessa categoria con alternative gratuite testate.
            </p>
            <div className="related-grid">
              {related.map(r => (
                <a key={r.id} href={`#/alternativa/${r.slug}`}
                   className="related-card"
                   onClick={(e)=>{e.preventDefault(); onNav(`/alternativa/${r.slug}`);}}
                   title={`Alternative gratis a ${r.nome}`}>
                  <Logo name={r.nome} size={36} url={r.sito_ufficiale} />
                  <div className="related-text">
                    <div className="related-name">Alternative gratis a {r.nome}</div>
                    <div className="related-meta">{r.alternative.length} testate · {r.categoria}</div>
                  </div>
                  <Icon.arrow />
                </a>
              ))}
            </div>
          </section>
        )}

        <section style={{padding:'32px 0 8px'}}>
          <div className="section-header" style={{marginBottom:16}}><h2>Continua a esplorare</h2></div>
          <div style={{display:'flex', gap:12, flexWrap:'wrap'}}>
            <a className="btn btn-outline" href={`#/categoria/${slugify(sw.categoria)}`} onClick={(e)=>{e.preventDefault(); onNav(`/categoria/${slugify(sw.categoria)}`);}}>Tutti i software in {sw.categoria}</a>
            <a className="btn btn-outline" href="#/software" onClick={(e)=>{e.preventDefault(); onNav('/software');}}>Tutti i software</a>
          </div>
        </section>
      </div>
    </div>
  );
}

function truncate(s, n) { if (!s) return ''; return s.length > n ? s.slice(0, n-1).trim() + '…' : s; }

function renderH1(h1, nome) {
  // Italicize "gratuite"/"gratis" inside the H1 to match the editorial style.
  const lower = h1.toLowerCase();
  const kw = lower.includes('gratuite') ? 'gratuite' : (lower.includes('gratis') ? 'gratis' : null);
  if (!kw) return h1;
  const idx = lower.indexOf(kw);
  return <>{h1.slice(0, idx)}<em>{h1.slice(idx, idx + kw.length)}</em>{h1.slice(idx + kw.length)}</>;
}

function injectSoftwareSchema(sw) {
  const alts = [...sw.alternative].sort((a,b)=>b.valutazione-a.valutazione);
  const monthly = parsePriceMonthly(sw.prezzo);
  const faqs = buildFaqs(sw, alts);

  const schemas = [
    // Primary paid SoftwareApplication (the one this page is ABOUT)
    softwareApplicationSchema(sw, {
      paidOffer: monthly ? { price: monthly.toFixed(2), currency: 'EUR' } : null,
    }),
    // ItemList of free alternatives
    alternativesItemList(sw, alts),
    // FAQ
    faqs.length ? faqPageSchema(faqs) : null,
    // Breadcrumb
    breadcrumbSchema([
      { name: 'Home', path: '/' },
      { name: sw.categoria, path: `/categoria/${slugify(sw.categoria)}` },
      { name: sw.nome, path: `/alternativa/${sw.slug}` },
    ]),
  ].filter(Boolean);

  setSchemas(schemas);
}

function AlternativeCard({ alt, rank, featured, paidMonthly }) {
  const savingYear = paidMonthly ? Math.round(paidMonthly * 12) : null;
  return (
    <article className={`alt-card ${featured ? 'featured' : ''}`}>
      <div className="alt-head">
        <Logo name={alt.nome} size={48} url={alt.sito_ufficiale} />
        <div className="alt-titlewrap">
          <h3>
            <span style={{color:'var(--ink-4)', fontWeight:500, marginRight:8}}>#{rank}</span>
            {alt.nome}
          </h3>
          <div style={{display:'flex', flexWrap:'wrap', gap:8, alignItems:'center', marginTop: 4}}>
            <AltBadges alt={alt} />
            {savingYear && <span className="save-inline">Risparmi €{formatEur(savingYear, 0)}/anno</span>}
          </div>
        </div>
        <Rating value={alt.valutazione} />
      </div>

      <p className="alt-desc">{alt.descrizione_it}</p>

      <div className="pros-cons">
        <div className="pros">
          <div className="head"><Icon.check />Punti di forza</div>
          <div>{alt.punti_forza}</div>
        </div>
        <div className="cons">
          <div className="head"><Icon.warn />Limiti</div>
          <div>{alt.limiti}</div>
        </div>
      </div>

      <div className="ideale">
        <strong style={{display:'inline-flex', alignItems:'center', gap:6}}><Icon.target/>Ideale per:</strong> {alt.ideale_per}
      </div>

      <div className="alt-foot">
        <div className="alt-foot-meta">
          <span style={{display:'inline-flex', alignItems:'center', gap:6}}>
            <span style={{fontWeight:500, color:'var(--ink-2)'}}>Piattaforme:</span>
            <Platforms list={alt.piattaforme} />
          </span>
        </div>
        <a className="btn btn-primary" href={alt.sito_ufficiale} target="_blank" rel="noopener noreferrer">
          Prova gratis <Icon.arrow />
        </a>
      </div>
    </article>
  );
}

function CompareTable({ alts, paid, paidMonthly }) {
  return (
    <div className="compare-wrap">
      <table className="compare">
        <thead>
          <tr>
            <th>Alternativa</th>
            <th>Prezzo</th>
            {paidMonthly && <th>Risparmio/anno</th>}
            <th>Open Source</th>
            <th>Valutazione</th>
          </tr>
        </thead>
        <tbody>
          {alts.map((a, i) => (
            <tr key={i}>
              <td className="nm">{a.nome}</td>
              <td><span style={{color:'#15803d', fontWeight:600}}>Gratis</span></td>
              {paidMonthly && <td><strong style={{color:'#15803d'}}>+€{formatEur(paidMonthly*12, 0)}</strong></td>}
              <td>{a.open_source ? <span className="check">✓</span> : <span className="dash">—</span>}</td>
              <td><Rating value={a.valutazione} /></td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function buildFaqs(sw, alts) {
  const best = alts[0];
  const openAlts = alts.filter(a=>a.open_source);
  const out = [
    {
      q: `Qual è la migliore alternativa gratuita a ${sw.nome}?`,
      a: `Per la maggior parte degli utenti consigliamo ${best.nome}: ${best.ideale_per.toLowerCase()}. Ha una valutazione di ${best.valutazione.toFixed(1)}/5 e ${best.open_source ? 'è open source' : 'offre un piano gratuito completo'}.`
    },
    {
      q: `Esistono alternative open source a ${sw.nome}?`,
      a: openAlts.length
        ? `Sì, tra le alternative testate ${openAlts.length === 1 ? 'c\'è' : 'ci sono'} ${openAlts.map(a=>a.nome).join(', ')}. Le soluzioni open source sono gratuite, trasparenti e spesso self-hostabili.`
        : `Tra le alternative selezionate in questa pagina non ci sono opzioni completamente open source, ma tutte offrono un piano gratuito utilizzabile.`
    },
    {
      q: `Le alternative a ${sw.nome} sono davvero gratis?`,
      a: `Sì. Ogni alternativa in questa lista è utilizzabile senza pagare. Alcune sono completamente gratuite e open source, altre sono freemium: il piano free copre la maggior parte degli usi, e i piani a pagamento aggiungono funzionalità avanzate per team o professionisti.`
    },
    {
      q: `Su quali piattaforme funzionano?`,
      a: `La disponibilità varia: in genere Windows, Mac, Linux, web e app mobili iOS/Android. Nella scheda di ogni alternativa trovi l'elenco preciso delle piattaforme supportate.`
    },
  ];
  return out;
}

function slugify(s) { return s.toLowerCase().replace(/[àáâä]/g,'a').replace(/[èéêë]/g,'e').replace(/[ìíîï]/g,'i').replace(/[òóôö]/g,'o').replace(/[ùúûü]/g,'u').replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,''); }

Object.assign(window, { SoftwarePage, AlternativeCard, CompareTable, slugify });
