const { useState, useEffect, useRef, useMemo } = React;

// ============ helpers ============
function parsePrice(str) {
  // Returns { min, max } in EUR, or null for non-numeric (Gratuita, %, etc.)
  if (!str) return null;
  const s = str.replace(/\./g, "").replace(/\s/g, "");
  // Match all numbers
  const nums = [...s.matchAll(/(\d+)/g)].map(m => parseInt(m[1], 10));
  if (nums.length === 0) return null;
  // Filter out tiny numbers from things like "10%" — if string contains %, skip
  if (s.includes("%")) return null;
  if (/^da/i.test(str.trim())) {
    return { min: nums[0], max: nums[0] * 1.6, fromOnly: true };
  }
  if (nums.length === 1) return { min: nums[0], max: nums[0] };
  return { min: nums[0], max: nums[1] };
}

function formatEuro(n) {
  return "€" + Math.round(n).toLocaleString("it-IT");
}

// ============ Cart Context (simple) ============
function useCart() {
  const [items, setItems] = useState([]);
  const add = (item) => setItems(prev => prev.find(i => i.id === item.id) ? prev : [...prev, item]);
  const remove = (id) => setItems(prev => prev.filter(i => i.id !== id));
  const has = (id) => items.some(i => i.id === id);
  return { items, add, remove, has };
}

// ============ Sidebar ============
function Sidebar({ active, onNavigate }) {
  const sections = window.NISBA_DATA.sections;
  const [menuOpen, setMenuOpen] = useState(false);

  const handleNav = (slug) => {
    setMenuOpen(false);
    onNavigate(slug);
  };

  const allNavItems = [
    ...sections.map(s => ({ slug: s.slug, num: s.n, title: s.title })),
    { slug: "pacchetti", num: "★", title: "Pacchetti consigliati" },
    { slug: "tariffario", num: "€/h", title: "Tariffario orario" },
  ];

  return (
    <>
      <aside className="sidebar">
        <div className="brand">
          <div className="logo-plate">
            <img src={window.NISBA_LOGO} alt="Nisba" />
          </div>
          <div className="tag">Prezziario · 2026</div>
        </div>
        <div className="bar"></div>
        <div>
          <div className="nav-label">Indice</div>
          <ul className="nav-list">
            {allNavItems.map(item => (
              <li key={item.slug}>
                <a
                  className={active === item.slug ? "active" : ""}
                  onClick={(e) => { e.preventDefault(); onNavigate(item.slug); }}
                  href={"#" + item.slug}
                >
                  <span className="num">{item.num}</span>
                  <span>{item.title}</span>
                </a>
              </li>
            ))}
          </ul>
        </div>
        <div className="side-foot">
          Documento interno di riferimento.<br/>
          I corrispettivi sono indicativi e modulabili.
        </div>
        <button className="menu-toggle" onClick={() => setMenuOpen(true)} aria-label="Apri menu">
          <svg width="22" height="14" viewBox="0 0 22 14" fill="none">
            <rect width="22" height="1.5" fill="currentColor"/>
            <rect y="6" width="22" height="1.5" fill="currentColor"/>
            <rect y="12" width="14" height="1.5" fill="currentColor"/>
          </svg>
          <span>Indice</span>
        </button>
      </aside>

      <nav className={"mobile-nav" + (menuOpen ? " open" : "")}>
        <div className="mn-head">
          <div className="mn-title">Indice</div>
          <button className="mn-close" onClick={() => setMenuOpen(false)} aria-label="Chiudi">×</button>
        </div>
        <ul className="mn-list">
          {allNavItems.map(item => (
            <li key={item.slug}>
              <a href={"#" + item.slug} onClick={(e) => { e.preventDefault(); handleNav(item.slug); }}>
                <span className="num">{item.num}</span>
                <span>{item.title}</span>
              </a>
            </li>
          ))}
        </ul>
      </nav>
    </>
  );
}

// ============ Hero ============
function Hero() {
  return (
    <section className="hero">
      <div className="eyebrow">
        <span className="line"></span>
        <span>Listino interno · v2026.01</span>
      </div>
      <div className="manifesto">
        <div className="manifesto-label">— Chi siamo</div>
        <p className="manifesto-text">
          <strong>Nisba</strong> nasce da un'idea semplice: al cliente <em>non serve nient'altro</em>. Niente fronzoli, niente moduli inutili, niente sovrastrutture da agenzia. Solo ciò che serve davvero, costruito su misura — sito, e-commerce, strategia, business plan, finanza agevolata — con la profondità di un partner e la leggerezza di chi sa dove guardare.
        </p>
        <div className="manifesto-etym">
          <span className="ety-key">nis·ba</span>
          <span className="ety-sep">·</span>
          <span className="ety-def">contrazione di <em>“non serve nient'altro”</em> — l'essenziale, fatto bene.</span>
        </div>
      </div>
      <h1>
        Servizi, valore<br/>
        e <em>misura giusta</em>.
      </h1>
      <p className="lede">
        Il presente prezziario rappresenta una base di riferimento interna per la formulazione di offerte, preventivi e proposte commerciali. I corrispettivi potranno essere adattati in base a complessità, urgenza, personalizzazioni e durata del progetto.
      </p>
      <div className="hero-meta">
        <div>
          <div className="k">Sezioni</div>
          <div className="v">10</div>
        </div>
        <div>
          <div className="k">Voci servizio</div>
          <div className="v">62</div>
        </div>
        <div>
          <div className="k">Pacchetti</div>
          <div className="v">5</div>
        </div>
        <div>
          <div className="k">Valuta</div>
          <div className="v">EUR</div>
        </div>
      </div>
    </section>
  );
}

// ============ Section ============
function Section({ section, cart }) {
  return (
    <section className="section" id={section.slug} data-section={section.slug}>
      <div className="section-head">
        <div className="section-num">{section.n}</div>
        <div className="section-title-row">
          <div className="section-kicker">Capitolo {section.n} · {section.items.length} voci</div>
          <h2 className="section-title">{section.title}</h2>
        </div>
        <div className="section-count">{String(section.items.length).padStart(2, "0")} / VOCI</div>
      </div>
      <div className="table">
        {section.items.map((item, i) => {
          const [name, price, note] = item;
          const id = `${section.slug}-${i}`;
          const inCart = cart.has(id);
          const featured = /gratuita|da €/i.test(price);
          return (
            <div
              key={id}
              className={"row" + (inCart ? " in-cart" : "")}
              onClick={() => inCart ? cart.remove(id) : cart.add({ id, name, price, category: section.title, parsed: parsePrice(price) })}
            >
              <span className="idx">{String(i + 1).padStart(2, "0")}</span>
              <div className="activity">{name}</div>
              <div className={"price" + (featured ? " featured" : "")}>{price}</div>
              <div className="note">{note}</div>
              <button className="add" aria-label={inCart ? "Rimuovi" : "Aggiungi"}>
                {inCart ? "✓" : "+"}
              </button>
            </div>
          );
        })}
      </div>
    </section>
  );
}

// ============ Packages ============
function PackagesSection({ cart }) {
  const pkgs = window.NISBA_DATA.packages;
  return (
    <section className="section" id="pacchetti" data-section="pacchetti" style={{ background: "var(--cream)" }}>
      <div className="section-head">
        <div className="section-num">★</div>
        <div className="section-title-row">
          <div className="section-kicker">Bundle · soluzioni preconfigurate</div>
          <h2 className="section-title">Pacchetti commerciali consigliati</h2>
        </div>
        <div className="section-count">{String(pkgs.length).padStart(2, "0")} / BUNDLE</div>
      </div>
      <div className="packages-grid">
        {pkgs.map((p, i) => (
          <div
            key={i}
            className={"pkg" + (i === 4 ? " featured" : "")}
            onClick={() => {
              const id = `pkg-${i}`;
              if (cart.has(id)) cart.remove(id);
              else cart.add({ id, name: p.name, price: p.price, category: "Pacchetto", parsed: parsePrice(p.price) });
            }}
            style={{ cursor: "pointer" }}
          >
            <div className="pkg-num">PKG · 0{i + 1}</div>
            <h3>{p.name}</h3>
            <p className="pkg-content">{p.content}</p>
            <div className="pkg-price">
              <em>Investimento</em>{p.price}
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

// ============ Hourly ============
function HourlySection() {
  const items = window.NISBA_DATA.hourly;
  return (
    <section className="section" id="tariffario" data-section="tariffario">
      <div className="section-head">
        <div className="section-num">€/h</div>
        <div className="section-title-row">
          <div className="section-kicker">Riferimento interno · per attività non a forfait</div>
          <h2 className="section-title">Tariffario orario</h2>
        </div>
        <div className="section-count">{String(items.length).padStart(2, "0")} / FASCE</div>
      </div>
      <div className="hourly-grid">
        {items.map((h, i) => (
          <div key={i} className="hourly-row">
            <span className="h-name">{h[0]}</span>
            <span className="h-rate">{h[1]}</span>
          </div>
        ))}
      </div>
    </section>
  );
}

// ============ Footer ============
function FooterNote() {
  return (
    <section className="foot-note">
      <div className="label">— Nota di chiusura</div>
      <p>
        “I prezzi indicati sono da intendersi come riferimento interno e potranno variare in funzione della complessità del progetto, dell'urgenza, delle personalizzazioni richieste e dell'eventuale continuità del rapporto.”
      </p>
      <div className="sign">
        <span>NISBA · Listino interno</span>
        <span>Edizione 2026 — v.01</span>
      </div>
    </section>
  );
}

// ============ Cart Panel ============
function CartPanel({ cart, open, onClose }) {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [message, setMessage] = useState("");
  const [sent, setSent] = useState(false);

  const totals = useMemo(() => {
    let min = 0, max = 0, hasUnknown = false, hasFrom = false;
    cart.items.forEach(i => {
      const p = i.parsed;
      if (!p) { hasUnknown = true; return; }
      min += p.min;
      max += p.max;
      if (p.fromOnly) hasFrom = true;
    });
    return { min, max, hasUnknown, hasFrom };
  }, [cart.items]);

  const totalText = cart.items.length === 0 ? "—" :
    (totals.min === totals.max ? formatEuro(totals.min) :
      `${formatEuro(totals.min)} – ${formatEuro(totals.max)}`);

  const handleSend = () => {
    if (cart.items.length === 0 && !message.trim()) return;
    const lines = [];
    lines.push("Richiesta di preventivo — Nisba");
    lines.push("=".repeat(40));
    lines.push("");
    if (name) lines.push(`Cliente: ${name}`);
    if (email) lines.push(`Email: ${email}`);
    if (name || email) lines.push("");
    lines.push("VOCI SELEZIONATE");
    lines.push("-".repeat(40));
    if (cart.items.length === 0) {
      lines.push("(nessuna voce selezionata dal listino)");
    } else {
      cart.items.forEach((i, idx) => {
        lines.push(`${String(idx + 1).padStart(2, "0")}. [${i.category}] ${i.name}`);
        lines.push(`    Prezzo indicativo: ${i.price}`);
      });
    }
    lines.push("");
    lines.push(`Totale stimato: ${totalText}`);
    if (totals.hasUnknown) lines.push("(+ voci a tariffa variabile)");
    lines.push("");
    if (message.trim()) {
      lines.push("ESIGENZE E DETTAGLI DEL CLIENTE");
      lines.push("-".repeat(40));
      lines.push(message.trim());
      lines.push("");
    }
    lines.push("—");
    lines.push("Inviato dal Prezziario Nisba · " + new Date().toLocaleDateString("it-IT"));

    const subject = `Richiesta preventivo Nisba${name ? " — " + name : ""}`;
    const body = lines.join("\n");
    const url = `mailto:amatoremanuele@gmail.com?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
    window.location.href = url;
    setSent(true);
    setTimeout(() => setSent(false), 4000);
  };

  const canSend = (cart.items.length > 0 || message.trim().length > 0);

  return (
    <>
      <div className={"cart-backdrop" + (open ? " open" : "")} onClick={onClose}></div>
      <aside className={"cart-panel" + (open ? " open" : "")}>
        <div className="cart-head">
          <div>
            <h2>Bozza preventivo</h2>
            <div className="sub">{cart.items.length} {cart.items.length === 1 ? "voce selezionata" : "voci selezionate"}</div>
          </div>
          <button className="cart-close" onClick={onClose} aria-label="Chiudi">×</button>
        </div>
        <div className="cart-body">
          {cart.items.length === 0 ? (
            <div className="cart-empty">
              <p>Seleziona le voci dal listino<br/>per comporre il preventivo.</p>
              <div className="cart-empty-hint">Oppure scrivi direttamente la tua esigenza qui sotto.</div>
            </div>
          ) : (
            <div className="cart-list">
              {cart.items.map(item => (
                <div key={item.id} className="cart-item">
                  <div>
                    <div className="ci-cat">{item.category}</div>
                    <div className="ci-name">{item.name}</div>
                    <div className="ci-price">{item.price}</div>
                  </div>
                  <button className="ci-rm" onClick={() => cart.remove(item.id)} aria-label="Rimuovi">×</button>
                </div>
              ))}
            </div>
          )}

          <div className="cart-form">
            <div className="form-label">— Raccontaci di te</div>
            <div className="form-row two">
              <input
                type="text"
                placeholder="Nome e cognome / Azienda"
                value={name}
                onChange={e => setName(e.target.value)}
              />
              <input
                type="email"
                placeholder="La tua email"
                value={email}
                onChange={e => setEmail(e.target.value)}
              />
            </div>
            <div className="form-row">
              <textarea
                placeholder="Spiega la tua esigenza: cosa vuoi realizzare, tempi, obiettivi, eventuali riferimenti. Più è chiaro, più la nostra proposta sarà su misura."
                value={message}
                onChange={e => setMessage(e.target.value)}
                rows={6}
              />
            </div>
            <div className="form-hint">
              La bozza sarà inviata a <span className="mono">amatoremanuele@gmail.com</span> tramite il tuo client di posta.
            </div>
          </div>
        </div>

        <div className="cart-foot">
          <div className="cart-total">
            <span className="k">Totale stimato</span>
            <span className="v">
              {totalText}
              {totals.hasUnknown && <small>+ voci a tariffa variabile</small>}
              {totals.hasFrom && !totals.hasUnknown && <small>indicativo</small>}
            </span>
          </div>
          <button
            className={"cta" + (canSend ? "" : " disabled")}
            onClick={handleSend}
            disabled={!canSend}
          >
            <span>{sent ? "✓ Email aperta" : "Invia richiesta di preventivo"}</span>
          </button>
        </div>
      </aside>
    </>
  );
}

// ============ App ============
function App() {
  const cart = useCart();
  const [active, setActive] = useState("consulenza");
  const [cartOpen, setCartOpen] = useState(false);
  const mainRef = useRef(null);

  const onNavigate = (slug) => {
    const el = document.getElementById(slug);
    if (el) {
      const top = el.getBoundingClientRect().top + window.scrollY - 24;
      window.scrollTo({ top, behavior: "smooth" });
    }
  };

  useEffect(() => {
    const handler = () => {
      const sections = document.querySelectorAll("[data-section]");
      let current = "consulenza";
      sections.forEach(s => {
        const r = s.getBoundingClientRect();
        if (r.top < window.innerHeight * 0.35) current = s.getAttribute("data-section");
      });
      setActive(current);
    };
    window.addEventListener("scroll", handler, { passive: true });
    handler();
    return () => window.removeEventListener("scroll", handler);
  }, []);

  return (
    <div className="app">
      <Sidebar active={active} onNavigate={onNavigate} />
      <main className="main" ref={mainRef}>
        <Hero />
        {window.NISBA_DATA.sections.map(s => (
          <Section key={s.slug} section={s} cart={cart} />
        ))}
        <PackagesSection cart={cart} />
        <HourlySection />
        <FooterNote />
      </main>
      <button className="cart-fab" onClick={() => setCartOpen(true)}>
        {cart.items.length === 0 ? (
          <>
            <span className="lbl-empty">Componi un preventivo</span>
            <span className="badge">+</span>
          </>
        ) : (
          <>
            <span>Bozza preventivo</span>
            <span className="badge">{cart.items.length}</span>
          </>
        )}
      </button>
      <CartPanel cart={cart} open={cartOpen} onClose={() => setCartOpen(false)} />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
