/* DockEasy — shared site chrome: nav, CTA band, footer */
const { motion: SM, useInView: useInViewS } = window.Motion;
const { useRef: useRefS, useState: useStateS } = window.React;

const DEMO_HREF = 'index.html#accesso';

/* Audience-aware navigation links */
const NAV_LINKS = {
  porti: [
    { label: 'Funzioni', href: 'funzioni.html', file: 'funzioni.html' },
    { label: 'Come funziona', href: 'come-funziona.html', file: 'come-funziona.html' },
  ],
  diportisti: [
    { label: 'Mappa', href: 'diportisti.html', file: 'diportisti.html' },
    { label: 'Come funziona', href: 'index.html#come-diportisti', file: 'index.html' },
  ],
};
const AUDIENCE_CTA = {
  porti: { label: 'Accesso early', short: 'Accesso', href: 'index.html#accesso' },
  diportisti: { label: 'Avvisami', short: 'Avvisami', href: 'index.html#ormeggio' },
};

function currentFile() {
  try { return decodeURIComponent((location.pathname.split('/').pop() || '')); } catch (e) { return ''; }
}
function storedView() {
  try { return localStorage.getItem('dockeasy-view') === 'diportisti' ? 'diportisti' : 'porti'; } catch (e) { return 'porti'; }
}

function SectionKicker({ children }) {
  return <div className="text-sm font-body text-teal mb-5 tracking-tight">// {children}</div>;
}

function NavToggle({ aud, onSwitch, full }) {
  const opts = [{ k: 'porti', l: 'Porti' }, { k: 'diportisti', l: 'Diportisti' }];
  return (
    <div className={(full ? 'flex w-full ' : 'inline-flex ') + 'glass rounded-full p-1 items-center gap-1'}>
      {opts.map((o) => {
        const on = aud === o.k;
        return (
          <button key={o.k} type="button" onClick={() => onSwitch(o.k)}
            className={(full ? 'flex-1 ' : '') + 'rounded-full px-4 py-2 text-sm font-medium font-body transition-colors whitespace-nowrap ' +
              (on ? 'bg-petrol text-white' : 'text-ink/60 hover:text-ink')}>
            {full ? 'Per i ' + o.l : o.l}
          </button>
        );
      })}
    </div>
  );
}

function SiteNav({ audience, onAudience }) {
  const [open, setOpen] = useStateS(false);
  const aud = audience || storedView();
  const cf = currentFile();
  const links = NAV_LINKS[aud];
  const cta = AUDIENCE_CTA[aud];

  const switchTo = (k) => {
    if (k === aud) return;
    if (onAudience) { onAudience(k); }
    else {
      try { localStorage.setItem('dockeasy-view', k); } catch (e) {}
      location.href = 'index.html' + (k === 'diportisti' ? '#diportisti' : '');
    }
    setOpen(false);
  };

  return (
    <div className="fixed top-4 inset-x-0 z-50 px-5 lg:px-10">
      <div className="flex lg:grid lg:grid-cols-[1fr_auto_1fr] items-center justify-between gap-4">
        <a href="index.html" className="flex items-center gap-2.5 shrink-0 lg:justify-self-start">
          <span className="glass w-11 h-11 rounded-full flex items-center justify-center">
            <img src="assets/logo-mark.svg" alt="" className="w-7 h-7" />
          </span>
          <span className="font-heading text-ink text-xl tracking-tight hidden sm:block">DockEasy</span>
        </a>

        {/* Desktop: audience toggle (always page-centered) */}
        <div className="hidden lg:flex lg:justify-self-center"><NavToggle aud={aud} onSwitch={switchTo} /></div>

        {/* Desktop: contextual links + CTA */}
        <nav className="hidden lg:flex items-center glass rounded-full p-1.5 gap-0.5 shrink-0 lg:justify-self-end">
          {links.map((l) => {
            const on = !l.href.includes('#') && l.file === cf;
            return (
              <a key={l.label} href={l.href}
                className={'px-3.5 py-2 text-sm font-medium font-body rounded-full transition-colors ' +
                  (on ? 'bg-white/70 text-petrol' : 'text-ink/70 hover:text-ink')}>
                {l.label}
              </a>
            );
          })}
          <a href={cta.href}
            className="ml-1 flex items-center gap-1.5 bg-coral text-white pl-4 pr-3 py-2 rounded-full text-sm font-semibold font-body whitespace-nowrap hover:brightness-105 transition">
            {cta.label}
            <Icon name="arrowUpRight" className="w-4 h-4" />
          </a>
        </nav>

        {/* Mobile / tablet cluster */}
        <div className="lg:hidden flex items-center gap-2">
          <a href={cta.href}
            className="flex items-center gap-1.5 bg-coral text-white px-4 py-2.5 rounded-full text-sm font-semibold font-body">
            {cta.short}
          </a>
          <button type="button" aria-label="Apri il menu" aria-expanded={open}
            onClick={() => setOpen((v) => !v)}
            className="glass w-11 h-11 rounded-full flex items-center justify-center text-ink">
            <Icon name={open ? 'close' : 'menu'} className="w-5 h-5" />
          </button>
        </div>
      </div>

      {/* Mobile / tablet dropdown */}
      {open ? (
        <div className="lg:hidden mt-2 glass-strong rounded-[1.25rem] p-2 flex flex-col gap-1">
          <div className="p-1"><NavToggle aud={aud} onSwitch={switchTo} full /></div>
          {links.map((l) => {
            const on = !l.href.includes('#') && l.file === cf;
            return (
              <a key={l.label} href={l.href} onClick={() => setOpen(false)}
                className={'flex items-center justify-between px-4 py-3 rounded-xl text-base font-medium font-body transition-colors ' +
                  (on ? 'bg-white/70 text-petrol' : 'text-ink/80 hover:bg-white/50')}>
                {l.label}
                <Icon name="arrowUpRight" className={'w-4 h-4 ' + (on ? 'text-petrol' : 'text-ink/40')} />
              </a>
            );
          })}
        </div>
      ) : null}
    </div>
  );
}

/* Petrol CTA band. Pass `form` JSX for the action area. */
function CTABand({ id, kicker, title, sub, form }) {
  const ref = useRefS(null);
  const inView = useInViewS(ref, { amount: 0.3, once: true });
  return (
    <section id={id} ref={ref} className="relative overflow-hidden" style={{ background: '#0B3C49' }}>
      <div className="absolute inset-0 pointer-events-none"
        style={{ background: 'radial-gradient(90% 120% at 80% 0%, rgba(63,193,201,0.22), rgba(11,60,73,0) 55%), radial-gradient(70% 80% at 10% 100%, rgba(19,122,134,0.35), rgba(11,60,73,0) 60%)' }} />
      <div className="relative z-10 px-5 md:px-12 lg:px-20 py-24 md:py-32 max-w-5xl mx-auto text-center">
        <SM.div
          initial={{ filter: 'blur(10px)', opacity: 0, y: 20 }}
          animate={inView ? { filter: 'blur(0px)', opacity: 1, y: 0 } : {}}
          transition={{ duration: 0.8, ease: [0.16, 1, 0.3, 1] }}
        >
          {kicker ? <span className="glass-dark rounded-full px-4 py-1.5 text-xs font-medium text-white/80 font-body">{kicker}</span> : null}
          <h2 className="font-heading text-white text-4xl md:text-6xl lg:text-[4.2rem] leading-[0.95] tracking-tight mt-7">{title}</h2>
          {sub ? <p className="text-white/70 font-body font-light text-base md:text-lg mt-5 max-w-xl mx-auto leading-snug">{sub}</p> : null}
          {form}
        </SM.div>
      </div>
    </section>
  );
}

function Badge({ kind }) {
  const map = { live: { t: 'Live', teal: true }, core: { t: 'Core', teal: true }, soon: { t: 'In arrivo', teal: false } };
  const b = map[kind] || map.soon;
  return (
    <span className={'inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[11px] font-semibold font-body ' +
      (b.teal ? 'bg-teal/15 text-teal' : 'bg-mist/15 text-mist')}>
      <span className={'w-1.5 h-1.5 rounded-full ' + (b.teal ? 'bg-teal' : 'bg-mist')}></span>
      {b.t}
    </span>
  );
}

const fieldCls = "glass-dark rounded-2xl px-5 py-3.5 text-sm font-body text-white placeholder-white/50 outline-none focus:ring-1 focus:ring-seaglass/60";

/* Lead form — PORTI. Obbligatori: nome porto + email. Facoltativi: città, posti, telefono. */
function DemoForm() {
  return (
    <React.Fragment>
      <form className="mt-10 max-w-lg mx-auto grid grid-cols-1 sm:grid-cols-2 gap-3 text-left" onSubmit={(e) => e.preventDefault()}>
        <input type="text" required placeholder="Nome del porto *" className={fieldCls} />
        <input type="email" required placeholder="Email di lavoro *" className={fieldCls} />
        <input type="text" placeholder="Città (facoltativo)" className={fieldCls} />
        <input type="text" placeholder="N° posti barca (facoltativo)" className={fieldCls} />
        <input type="tel" placeholder="Telefono (facoltativo)" className={fieldCls + ' sm:col-span-2'} />
        <button type="submit"
          className="sm:col-span-2 flex items-center justify-center gap-2 bg-coral text-white px-6 py-3.5 rounded-full text-sm font-semibold font-body hover:brightness-105 transition">
          Richiedi l’accesso early
          <Icon name="arrowUpRight" className="w-4 h-4" />
        </button>
      </form>
      <p className="text-white/45 text-xs font-body mt-4">* campi obbligatori · Ti scriviamo quando apriamo l’accesso early. Niente spam.</p>
    </React.Fragment>
  );
}

/* Lead form — DIPORTISTI. Obbligatorio: email. Facoltativi: nome, barca, zona. */
function BoaterForm() {
  return (
    <React.Fragment>
      <form className="mt-10 max-w-lg mx-auto grid grid-cols-1 sm:grid-cols-2 gap-3 text-left" onSubmit={(e) => e.preventDefault()}>
        <input type="email" required placeholder="Email *" className={fieldCls + ' sm:col-span-2'} />
        <input type="text" placeholder="Nome (facoltativo)" className={fieldCls} />
        <input type="text" placeholder="Barca · lunghezza in m (facoltativo)" className={fieldCls} />
        <input type="text" placeholder="Zona preferita (facoltativo)" className={fieldCls + ' sm:col-span-2'} />
        <button type="submit"
          className="sm:col-span-2 flex items-center justify-center gap-2 bg-coral text-white px-6 py-3.5 rounded-full text-sm font-semibold font-body hover:brightness-105 transition">
          Avvisami quando posso prenotare
          <Icon name="arrowUpRight" className="w-4 h-4" />
        </button>
      </form>
      <p className="text-white/55 text-xs font-body mt-4">
        * campo obbligatorio · Intanto esplora la <a href="diportisti.html#mappa" className="text-seaglass hover:text-white">mappa libera</a>. Niente spam.
      </p>
    </React.Fragment>
  );
}

const FOOTER_COLS = [
  { title: 'Prodotto', links: [{ label: 'Funzioni', href: 'funzioni.html' }, { label: 'Come funziona', href: 'come-funziona.html' }, { label: 'Prezzi', href: 'index.html#prezzi' }, { label: 'Per i diportisti', href: 'diportisti.html' }] },
  { title: 'Azienda', links: [{ label: 'Accesso early', href: DEMO_HREF }, { label: 'Contatti', href: DEMO_HREF }, { label: 'Privacy', href: '#' }] },
];

function SiteFooter() {
  return (
    <footer className="relative z-10 px-5 md:px-12 lg:px-20 pt-14 pb-10" style={{ background: '#0B3C49' }}>
      <div className="max-w-6xl mx-auto">
        <div className="grid grid-cols-2 md:grid-cols-4 gap-8 pb-10">
          <div className="col-span-2 md:col-span-2">
            <a href="index.html" className="flex items-center gap-2.5">
              <span className="glass-dark w-9 h-9 rounded-full flex items-center justify-center">
                <img src="assets/logo-mark.svg" alt="" className="w-6 h-6" />
              </span>
              <span className="font-heading text-white text-lg tracking-tight">DockEasy</span>
            </a>
            <p className="text-white/55 text-sm font-body font-light mt-4 max-w-xs leading-snug">
              Il sistema per gestire il tuo porto. Semplice, moderno, mediterraneo.
            </p>
            <div className="flex items-center gap-1 mt-6">
              <span className="text-white/40 text-xs font-body mr-2">Lingua</span>
              <button className="rounded-full px-3 py-1 text-xs font-body bg-white/15 text-white">IT</button>
              <button className="rounded-full px-3 py-1 text-xs font-body text-white/45 hover:text-white/70 transition" title="In arrivo">EN</button>
            </div>
          </div>
          {FOOTER_COLS.map((col) => (
            <div key={col.title}>
              <div className="text-white/45 text-xs font-body uppercase tracking-wide mb-4">{col.title}</div>
              <div className="flex flex-col gap-2.5">
                {col.links.map((l) => (
                  <a key={l.label} href={l.href} className="text-sm font-body text-white/70 hover:text-white transition">{l.label}</a>
                ))}
              </div>
            </div>
          ))}
        </div>
        <div className="border-t border-white/10 pt-6 flex flex-col sm:flex-row items-center justify-between gap-3">
          <span className="text-white/40 text-xs font-body">© 2026 DockEasy — un progetto MFF Projects</span>
          <span className="text-white/40 text-xs font-body">Accesso early · Mediterraneo</span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { SectionKicker, Badge, NavToggle, SiteNav, CTABand, DemoForm, BoaterForm, SiteFooter });
