// Shared chrome: transforming navbar + footer + global project-builder drawer.
//
// Scroll-driven nav morph:
//   0       → horizontal bar at top, all labels visible
//   0→1     → labels fly from their h-link centres to their v-icon centres,
//              text fades out, icon fades in, slight upward arc for feel
//   1       → vertical rail locked in on the right, labels gone

// ── Wand icon (inline SVG, not in PDAIcons) ─────────────────────────────────
function WandIcon({ size = 20 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 20 20" fill="none"
      stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"
      aria-hidden="true">
      <line x1="2.5" y1="17.5" x2="10" y2="10" />
      <path d="M12 2.5 L13.2 5.8 L16.5 7 L13.2 8.2 L12 11.5 L10.8 8.2 L7.5 7 L10.8 5.8 Z" />
    </svg>
  );
}

// ── Project Builder Drawer ───────────────────────────────────────────────────
function ProjectBuilderDrawer({ open, onClose }) {
  const I = window.PDAIcons;
  const C = window.PDABuilderCore;
  const [step, setStep] = React.useState(0);
  const [answers, setAnswers] = React.useState({ extras: [] });
  const [done, setDone] = React.useState(false);
  const [submitted, setSubmitted] = React.useState(false);
  const [loading, setLoading] = React.useState(false);
  const [formError, setFormError] = React.useState('');

  React.useEffect(() => {
    if (!open) return;
    setStep(0); setAnswers({ extras: [] }); setDone(false); setSubmitted(false); setLoading(false); setFormError('');
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [open]);

  if (!open || !C) return null;

  const steps = C.PB_STEPS;
  const stepDef = steps[step];
  const total = steps.length;
  const rec = done ? C.getRecommendation(answers) : null;

  const choose = (val) => {
    if (stepDef.multi) {
      const cur = answers[stepDef.key] || [];
      const next = val === 'none' ? ['none']
        : cur.includes(val) ? cur.filter(v => v !== val)
        : [...cur.filter(v => v !== 'none'), val];
      setAnswers({ ...answers, [stepDef.key]: next });
    } else {
      setAnswers({ ...answers, [stepDef.key]: val });
      setTimeout(() => {
        if (step + 1 >= total) setDone(true);
        else setStep(step + 1);
      }, 250);
    }
  };

  const advanceMulti = () => { if (step + 1 >= total) setDone(true); else setStep(step + 1); };
  const goBack = () => { if (done) { setDone(false); return; } if (step > 0) setStep(step - 1); };
  const reset = () => { setStep(0); setAnswers({ extras: [] }); setDone(false); setSubmitted(false); };

  return ReactDOM.createPortal(
    <div className="drawer-root">
      <div className="drawer-backdrop" onClick={onClose} />
      <div className="drawer-panel" role="dialog" aria-modal="true" aria-label="Project Builder">
        <div className="drawer-header">
          <div>
            <span className="eyebrow" style={{ fontSize: 10 }}>Project Builder</span>
            <h2 className="drawer-title">Find your fit.</h2>
          </div>
          <button className="drawer-close" onClick={onClose} aria-label="Close">
            <I.X size={18} />
          </button>
        </div>

        <div className="drawer-body">
          {/* Progress */}
          <div className="drawer-progress">
            {steps.map((s, i) => (
              <span key={i} className={'drawer-dot' + (i === step && !done ? ' active' : '') + (i < step || done ? ' done' : '')}>
                {i < step || done ? <I.Check size={10} /> : i + 1}
              </span>
            ))}
            <span className={'drawer-dot' + (done ? ' active' : '')}>
              {done && !submitted ? <I.Sparkle size={10} /> : submitted ? <I.Check size={10} /> : total + 1}
            </span>
          </div>

          {/* Steps */}
          {!done && (
            <>
              <div className="pb-step-head">
                <span className="eyebrow" style={{ fontSize: 10 }}>Step {step + 1} of {total}</span>
                <h3 style={{ fontSize: 20, margin: 0 }}>{stepDef.head}</h3>
                <p style={{ fontSize: 13, margin: 0 }}>{stepDef.sub}</p>
              </div>
              <div className="pb-choices">
                {stepDef.choices.map((c) => {
                  const Icon = I[c.icon];
                  const selected = stepDef.multi
                    ? (answers[stepDef.key] || []).includes(c.v)
                    : answers[stepDef.key] === c.v;
                  return (
                    <button key={c.v} className={'pb-choice' + (selected ? ' selected' : '')} onClick={() => choose(c.v)}>
                      <div className="pb-choice-head">
                        <span className="pb-choice-icon"><Icon size={16} /></span>
                        <span className="pb-choice-check">{selected ? <I.Check size={12} /> : null}</span>
                      </div>
                      <span className="pb-choice-name" style={{ fontSize: 14 }}>{c.name}</span>
                      <span className="pb-choice-desc" style={{ fontSize: 12 }}>{c.desc}</span>
                    </button>
                  );
                })}
              </div>
              <div className="pb-foot">
                <button className="pb-skip" onClick={goBack} disabled={step === 0} style={{ opacity: step === 0 ? .3 : 1 }}>← Back</button>
                {stepDef.multi
                  ? <button className="btn btn-primary btn-sm" onClick={advanceMulti}><span className="btn-label">Continue</span><I.Arrow size={12} /></button>
                  : <span style={{ fontSize: 12, color: 'var(--fg-3)' }}>Tap a choice to continue</span>
                }
              </div>
            </>
          )}

          {/* Result */}
          {done && !submitted && rec && (
            <>
              <div className="pb-step-head">
                <span className="eyebrow" style={{ fontSize: 10 }}>Our honest recommendation</span>
                <h3 style={{ fontSize: 20, margin: 0 }}>
                  We'd suggest <span className="gradient-text">{rec.pkg}</span>.
                </h3>
              </div>
              <p style={{ fontSize: 14, lineHeight: 1.65, color: 'var(--fg-2)', margin: 0 }}>{rec.blurb}</p>
              {C.SOCIAL_PROOF[rec.slug] && (
                <blockquote className="drawer-proof">{C.SOCIAL_PROOF[rec.slug]}</blockquote>
              )}
              <a className="btn btn-outline btn-sm" href={'packages.html#' + rec.slug} style={{ alignSelf: 'flex-start' }}>
                <span className="btn-label">See package detail</span>
              </a>
              <div className="drawer-contact-form">
                <h4 style={{ fontSize: 13, fontWeight: 600, color: 'var(--fg-1)', margin: '0 0 14px' }}>Want to talk about this?</h4>
                <form onSubmit={async (e) => {
                  e.preventDefault();
                  setLoading(true); setFormError('');
                  const els = e.target.elements;
                  const name = els.name.value.trim();
                  const business = els.business.value.trim();
                  const email = els.email.value.trim();
                  const notes = (els.notes?.value ?? '').trim();
                  try {
                    const res = await fetch('/api/leads', {
                      method: 'POST',
                      headers: { 'Content-Type': 'application/json' },
                      body: JSON.stringify({ name, business, email, notes, builderAnswers: answers, packageRecommendation: rec.slug }),
                    });
                    if (!res.ok) throw new Error();
                    try {
                      localStorage.setItem('pda_builder_submitted', String(Date.now()));
                      localStorage.setItem('pda_builder_contact', JSON.stringify({ name, email, business, phone: '' }));
                    } catch (_) {}
                    if (C) C.clearProgress();
                    setSubmitted(true);
                  } catch {
                    setFormError('Something went wrong. Try again or email us directly.');
                    setLoading(false);
                  }
                }} style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                  <div style={{ display: 'flex', gap: 10 }}>
                    <div className="field" style={{ flex: 1 }}>
                      <label>Name</label>
                      <input required name="name" type="text" placeholder="Tom Addison" />
                    </div>
                    <div className="field" style={{ flex: 1 }}>
                      <label>Business</label>
                      <input required name="business" type="text" placeholder="Addison Excavations" />
                    </div>
                  </div>
                  <div className="field">
                    <label>Email</label>
                    <input required name="email" type="email" placeholder="tom@addison.co" />
                  </div>
                  <div className="field">
                    <label>Anything else? <span style={{ color: 'var(--fg-3)', fontWeight: 400 }}>(optional)</span></label>
                    <textarea name="notes" placeholder={'E.g. I want to talk about the ' + rec.pkg + ' path..'} rows={3} style={{ resize: 'none' }} />
                  </div>
                  {formError && <p style={{ margin: 0, fontSize: 12, color: '#e05c5c' }}>{formError}</p>}
                  <button className="btn btn-primary" type="submit" disabled={loading} style={{ opacity: loading ? .6 : 1 }}>
                    <span className="btn-label">{loading ? 'Sending…' : 'Send + book a call'}</span>
                    {!loading && <I.Arrow size={14} />}
                  </button>
                  <span style={{ fontSize: 11, color: 'var(--fg-3)' }}>Your answers will be attached. We never sell or share contact info.</span>
                </form>
              </div>
              <div className="pb-foot">
                <button className="pb-skip" onClick={goBack}>← Edit answers</button>
                <button className="pb-skip" onClick={reset}>Start over</button>
              </div>
            </>
          )}

          {/* Success */}
          {submitted && (
            <div style={{ padding: '40px 0', textAlign: 'center', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14 }}>
              <span className="contact-thanks-icon"><I.Check size={24} /></span>
              <h3 style={{ margin: 0, fontSize: 22, fontWeight: 700, letterSpacing: '-.015em' }}>Got it. Talk soon.</h3>
              <p style={{ margin: 0, fontSize: 14, color: 'var(--fg-2)', lineHeight: 1.55, maxWidth: 300 }}>
                Eric will reach out within one business day. Filling out the intake form before your call saves 15–20 minutes — most clients do it the same day.
              </p>
              <a className="btn btn-primary btn-sm" href="discovery.html" style={{ marginTop: 8 }}>
                <span className="btn-label">Get a head start on your intake form</span>
                <I.Arrow size={12} />
              </a>
              <button className="btn btn-outline btn-sm" onClick={reset}>
                <span className="btn-label">Start a new inquiry</span>
              </button>
            </div>
          )}
        </div>
      </div>
    </div>,
    document.body
  );
}

const NAV_ITEMS = [
  { label: 'Services',     href: 'services.html',     icon: 'Tools'     },
  { label: 'Portfolio',    href: 'portfolio.html',    icon: 'Briefcase' },
  { label: 'Packages',     href: 'packages.html',     icon: 'Stack'     },
  { label: 'Skeleton Key', href: 'skeleton-key.html', icon: 'Link'      },
  { label: 'About',        href: 'about.html',        icon: 'Compass'   },
  { label: 'Resources',    href: 'resources.html',    icon: 'Book'      },
  { label: 'Contact',      href: 'contact.html',      icon: 'Mail'      },
];

const SCROLL_START = 60;
const SCROLL_END   = 900;

function eio(t) { return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t; }
function lerp(a, b, t) { return a + (b - a) * t; }
function remap(x, lo, hi, oLo, oHi) {
  return oLo + (oHi - oLo) * Math.max(0, Math.min(1, (x - lo) / (hi - lo)));
}

function PDANav({ active = '', basePath = '' }) {
  const I = window.PDAIcons;
  const [prog, setProg] = React.useState(0);
  const [drawerOpen, setDrawerOpen] = React.useState(false);
  const contentUrl = window.PDAContentUrl || ((key, fallback) => fallback);
  const logoIcon = contentUrl('brand.navbar_logo', basePath + 'assets/logo-icon.png');

  // Keep the nav horizontal (no morph) while the user is filling out a form.
  const isFormPage = ['discovery.html', 'contact.html', 'start.html'].some(
    p => window.location.pathname.includes(p),
  );

  React.useEffect(() => {
    window.PDAOpenBuilder = () => setDrawerOpen(true);
    return () => { delete window.PDAOpenBuilder; };
  }, []);

  const hRefs  = React.useRef([]);  // h-nav link elements
  const vRefs  = React.useRef([]);  // v-rail icon link elements
  const vRailR = React.useRef(null);
  const posC   = React.useRef(null); // cached FROM/TO positions

  // ── Position measurement ─────────────────────────────────────────────────
  // Temporarily move v-rail to its fully-shown position (invisible),
  // grab bounding rects, then restore. Called once at mount + on resize.
  const measure = React.useCallback(() => {
    const vRail = vRailR.current;
    if (!vRail) return;

    const saved = {
      transform:     vRail.style.transform,
      opacity:       vRail.style.opacity,
      transition:    vRail.style.transition,
      pointerEvents: vRail.style.pointerEvents,
    };
    vRail.style.transition    = 'none';
    vRail.style.transform     = 'translateY(-50%) translateX(0)';
    vRail.style.opacity       = '0';
    vRail.style.pointerEvents = 'none';
    void vRail.offsetWidth; // force layout

    posC.current = NAV_ITEMS.map((_, i) => {
      const hEl = hRefs.current[i];
      const vEl = vRefs.current[i];
      if (!hEl || !vEl) return null;
      const hr = hEl.getBoundingClientRect();
      const vr = vEl.getBoundingClientRect();
      return {
        fromX: hr.left + hr.width  / 2,
        fromY: hr.top  + hr.height / 2,
        toX:   vr.left + vr.width  / 2,
        toY:   vr.top  + vr.height / 2,
      };
    });

    Object.assign(vRail.style, saved);
  }, []);

  React.useEffect(() => {
    const t = setTimeout(measure, 350);
    window.addEventListener('resize', measure);
    return () => { clearTimeout(t); window.removeEventListener('resize', measure); };
  }, [measure]);

  // ── Scroll tracking ───────────────────────────────────────────────────────
  React.useEffect(() => {
    if (isFormPage) return; // freeze nav at horizontal — no morph during form fills
    const onScroll = () => {
      const raw = Math.max(0, Math.min(1,
        (window.scrollY - SCROLL_START) / (SCROLL_END - SCROLL_START)));
      setProg(raw);
      document.body.classList.toggle('scrolled', raw >= 1);
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, [isFormPage]);

  const ep   = eio(prog);            // eased 0→1
  const inT  = prog > 0.03 && prog < 0.97; // actively transitioning
  const link = (href) => basePath + href;

  return (
    <div className="nav-host">
      <a className="skip-link" href="#app">Skip to main content</a>

      {/* ── Horizontal bar ─────────────────────────────────────────────── */}
      <header className="nav-h" style={{
        opacity:       Math.max(0, 1 - ep * 1.6),
        transform:     `translateY(${-ep * 100}%)`,
        pointerEvents: ep > 0.35 ? 'none' : 'auto',
        transition:    'none',
      }}>
        <div className="container nav-h-inner">
          <a className="nav-brand" href={link('index.html')} aria-label="PDA home">
            <span className="logo-wrap">
              <img src={logoIcon} alt="" />
            </span>
            <span className="brand-mark">
              <span className="top">P.D.A.</span>
              <span className="bot">Building Since 2020</span>
            </span>
          </a>
          <nav className="nav-h-links">
            {NAV_ITEMS.map((it, i) =>
              <a key={it.label}
                href={link(it.href)}
                className={active === it.label ? 'active' : ''}
                ref={el => { hRefs.current[i] = el; }}
                style={{ opacity: inT ? 0 : 1, transition: 'none' }}
              >{it.label}</a>
            )}
          </nav>
          <div className="nav-h-cta">
            <button className="btn btn-outline btn-sm nav-build-btn" onClick={() => setDrawerOpen(true)}>
              <WandIcon size={14} />
              <span className="btn-label">Hire us</span>
              <span className="nav-cta-arrow" aria-hidden="true">&rarr;</span>
            </button>
          </div>
        </div>
      </header>

      {/* ── Vertical rail ──────────────────────────────────────────────── */}
      <nav className="nav-v" ref={vRailR}
        aria-label="Site navigation rail"
        style={{
          opacity:       Math.min(1, Math.max(0, ep * 2.2 - 0.9)),
          transform:     `translateY(-50%) translateX(${(1 - ep) * 120}%)`,
          pointerEvents: ep > 0.88 ? 'auto' : 'none',
          transition:    'none',
        }}>
        <a href={link('index.html')} className="v-logo" aria-label="Home">
          <img src={logoIcon} alt="PDA" />
        </a>
        <span className="v-divider" />
        {NAV_ITEMS.map((it, i) => {
          const IconComp = I[it.icon];
          return (
            <a key={it.label}
              href={link(it.href)}
              className={'v-link' + (active === it.label ? ' active' : '')}
              ref={el => { vRefs.current[i] = el; }}
              style={{ opacity: inT ? 0 : 1, transition: 'none' }}
            >
              <IconComp size={20} />
              <span className="v-tip">{it.label}</span>
            </a>
          );
        })}
        <span className="v-divider" />
        <button className="v-cta v-wand" onClick={() => setDrawerOpen(true)} aria-label="Open project builder">
          <WandIcon size={18} />
          <span className="v-tip">Hire us</span>
        </button>
      </nav>

      {/* ── Morph tokens — fly from h-link → v-icon ────────────────────── */}
      {inT && posC.current && (
        <div className="nav-morph-layer" aria-hidden="true">
          {NAV_ITEMS.map((it, i) => {
            const pos = posC.current[i];
            if (!pos) return null;
            const IconComp = I[it.icon];

            // Position: straight-line lerp + upward arc peak at midpoint
            const x   = lerp(pos.fromX, pos.toX, ep);
            const arc = Math.sin(ep * Math.PI) * -30;
            const y   = lerp(pos.fromY, pos.toY, ep) + arc;

            // Crossfade: text out first 40%, icon in from 60%
            const tA = remap(ep, 0,    0.40, 1, 0);
            const iA = remap(ep, 0.60, 1.0,  0, 1);

            return (
              <div key={it.label} className="nav-morph-token"
                style={{ transform: `translate(${x}px,${y}px) translate(-50%,-50%)` }}>
                <span className="morph-text"  style={{ opacity: tA }}>{it.label}</span>
                <span className="morph-icon"  style={{ opacity: iA }}>
                  <IconComp size={20} />
                </span>
              </div>
            );
          })}
        </div>
      )}

      <ProjectBuilderDrawer open={drawerOpen} onClose={() => setDrawerOpen(false)} />
    </div>
  );
}

function PDAFooter({ basePath = '' }) {
  const I = window.PDAIcons;
  const contentUrl = window.PDAContentUrl || ((key, fallback) => fallback);
  const logoIcon = contentUrl('brand.navbar_logo', basePath + 'assets/logo-icon.png');
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div className="footer-brand-block">
            <div className="logo-row">
              <img src={logoIcon} alt="" />
              <span className="name">PANOPTIC DIGITAL ARCHITECTURE</span>
            </div>
            <p>Your partner in tech. We build the digital systems that put good businesses in front of the customers they've already earned.</p>
            <div style={{ display: 'flex', gap: 14, color: 'var(--fg-3)', fontSize: 13, alignItems: 'center' }}>
              <I.Map size={14} />
              <span>Based in North Georgia</span>
            </div>
          </div>

          <div className="footer-col">
            <h4>Services</h4>
            <ul>
              <li><a href={basePath + 'services.html#web'}>Web development</a></li>
              <li><a href={basePath + 'services.html#seo'}>SEO &amp; GEO</a></li>
              <li><a href={basePath + 'services.html#automation'}>Automation</a></li>
              <li><a href={basePath + 'services.html#ecosystem'}>Digital ecosystem</a></li>
              <li><a href={basePath + 'services.html#dashboards'}>Dashboards</a></li>
              <li><a href={basePath + 'services.html#content'}>Content &amp; blog</a></li>
            </ul>
          </div>

          <div className="footer-col">
            <h4>Packages</h4>
            <ul>
              <li><a href={basePath + 'packages.html#foundation'}>Foundation</a></li>
              <li><a href={basePath + 'packages.html#growth'}>Growth</a></li>
              <li><a href={basePath + 'packages.html#operation'}>Operation</a></li>
              <li><a href={basePath + 'packages.html#automation'}>Automation</a></li>
              <li><a href={basePath + 'packages.html#custom'}>Custom build</a></li>
            </ul>
          </div>

          <div className="footer-col">
            <h4>Company</h4>
            <ul>
              <li><a href={basePath + 'about.html'}>About</a></li>
              <li><a href={basePath + 'portfolio.html'}>Portfolio</a></li>
              <li><a href={basePath + 'skeleton-key.html'}>The Skeleton Key</a></li>
              <li><a href={basePath + 'resources.html'}>Resources</a></li>
              <li><a href={basePath + 'contact.html'}>Contact</a></li>
              <li><a href={basePath + 'contact.html#referral'}>Refer a friend</a></li>
            </ul>
          </div>

          <div className="footer-col">
            <h4>Get in touch</h4>
            <ul>
              <li><a href="mailto:contact@panoptic360.com">contact@panoptic360.com</a></li>
              <li><a href="tel:+12132451345">(213) 245-1345</a></li>
              <li><a href={basePath + 'contact.html'}>Project builder &nbsp;→</a></li>
              <li><a href={basePath + 'start.html'}>Get started &nbsp;→</a></li>
              <li><a href={basePath + 'discovery.html'}>New client intake &nbsp;→</a></li>
            </ul>
          </div>
        </div>

        <div className="footer-meta">
          <span>© {new Date().getFullYear()} Panoptic Digital Architecture, LLC. All rights reserved.</span>
          <div className="legal-links">
            <a href={basePath + 'privacy.html'}>Privacy</a>
            <a href={basePath + 'terms.html'}>Terms</a>
            <a href={basePath + 'sitemap.xml'}>Sitemap</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

window.PDANav    = PDANav;
window.PDAFooter = PDAFooter;

// Generic reveal-on-scroll utility
window.initReveal = () => {
  const els = document.querySelectorAll('.reveal:not(.in)');
  if (!('IntersectionObserver' in window)) {
    els.forEach((el) => el.classList.add('in'));
    return;
  }
  const io = new IntersectionObserver((entries) => {
    entries.forEach((e) => { if (e.isIntersecting) { e.target.classList.add('in'); io.unobserve(e.target); } });
  }, { threshold: 0.05, rootMargin: '0px 0px 200px 0px' });
  els.forEach((el) => io.observe(el));
  setTimeout(() => document.querySelectorAll('.reveal:not(.in)').forEach((el) => el.classList.add('in')), 1600);
};
