// Shared shell components for the multi-page Prospec & Design site.
// Used by every page: Header (with Services dropdown + lang toggle + mobile menu),
// Footer, PageHero, CTABanner.
//
// Conventions:
//   - Each page sets `data-page="home|about|services|service-detail|projects|blog|quote|contact"`
//     and `data-service="<slug>"` on the root mount node.
//   - Language is persisted in localStorage under "pd-lang" (default "en").
//
// Usage in a page-specific JSX file:
//   const root = ReactDOM.createRoot(document.getElementById("app"));
//   const App = () => {
//     const [lang, setLang] = useLang();
//     const t = mergeT(lang); // merges old I18N + new I18N_PAGES under one object
//     return (
//       <>
//         <Header lang={lang} setLang={setLang} t={t} active="about" />
//         <PageHero lang={lang} t={t.about_page} crumbs={[{label: t.about_page.crumb}]} />
//         ...page content...
//         <CTABanner t={t} />
//         <Footer lang={lang} t={t} />
//       </>
//     );
//   };

// =============== HOOKS ===============
const useLang = () => {
  const [lang, set] = React.useState(() => {
    try { return localStorage.getItem('pd-lang') || 'en'; } catch (e) { return 'en'; }
  });
  const setLang = (l) => {
    set(l);
    try { localStorage.setItem('pd-lang', l); } catch (e) {}
    document.documentElement.setAttribute('lang', l);
  };
  React.useEffect(() => {
    document.documentElement.setAttribute('lang', lang);
  }, [lang]);
  return [lang, setLang];
};

// Merge legacy I18N (home page strings) with new I18N_PAGES so every page can
// access both shapes via a single `t` object.
const mergeT = (lang) => {
  const a = (window.I18N && window.I18N[lang]) || {};
  const b = (window.I18N_PAGES && window.I18N_PAGES[lang]) || {};
  return { ...a, ...b, _lang: lang };
};

// =============== HEADER ===============
const Header = ({ lang, setLang, t, active }) => {
  const [open, setOpen] = React.useState(false);
  const [svcOpen, setSvcOpen] = React.useState(false);
  const services = window.SERVICE_KEYS;
  const meta = t.services_meta || {};
  const navT = t.nav || {};
  return (
    <>
      <header className="nav">
        <div className="container nav-inner">
          <a href="index.html" className="logo">
            <div className="logo-mark">P&amp;D</div>
            <div className="logo-text">
              <div className="logo-name">PROSPEC &amp; DESIGN</div>
              <div className="logo-tag">REMODELING · AUSTIN TX</div>
            </div>
          </a>

          <nav className="nav-links" aria-label="Primary">
            <a href="index.html"   className={"nav-link" + (active === "home" ? " active" : "")}>{navT.home}</a>
            <a href="about.html"   className={"nav-link" + (active === "about" ? " active" : "")}>{navT.about}</a>
            <div
              className={"nav-item" + (svcOpen ? " open" : "")}
              onMouseEnter={() => setSvcOpen(true)}
              onMouseLeave={() => setSvcOpen(false)}
            >
              <button
                className={"nav-trigger" + (active === "services" || active === "service-detail" ? " active" : "")}
                onClick={() => setSvcOpen(v => !v)}
                aria-expanded={svcOpen}
              >
                {navT.services} <Icon.ChevronDown size={12} />
              </button>
              <div className="nav-dropdown" role="menu">
                <a href="services.html" style={{ borderBottom: "1px solid var(--line)", paddingBottom: 12, marginBottom: 6, fontWeight: 700 }}>
                  <span className="ic"><Icon.Sparkle size={16} /></span>
                  {navT.services} — {lang === 'en' ? 'all services' : 'todos'}
                </a>
                {services.map(slug => {
                  const m = meta[slug] || { title: slug };
                  const ServiceIc = Icon[ {
                    'residential': 'House',
                    'commercial':  'Building',
                    'kitchen':     'Kitchen',
                    'bathroom':    'Bath',
                    'whole-home':  'Sparkle',
                    'carpentry':   'Carpentry',
                    'finish':      'Finish',
                    'management':  'Clipboard',
                  }[slug] ] || Icon.Construction;
                  return (
                    <a key={slug} href={`service-${slug}.html`} role="menuitem">
                      <span className="ic"><ServiceIc size={16} /></span>
                      <span>
                        <div style={{ fontWeight: 600 }}>{m.title}</div>
                        <div style={{ fontSize: 12, color: "var(--ink-2)", fontWeight: 400 }}>{m.short}</div>
                      </span>
                    </a>
                  );
                })}
                <div
                  className="nav-dropdown-foot"
                  dangerouslySetInnerHTML={{ __html: navT.services_foot }}
                />
              </div>
            </div>
            <a href="projects.html" className={"nav-link" + (active === "projects" ? " active" : "")}>{navT.projects}</a>
            <a href="blog.html"     className={"nav-link" + (active === "blog" ? " active" : "")}>{navT.blog}</a>
            <a href="contact.html"  className={"nav-link" + (active === "contact" ? " active" : "")}>{navT.contact}</a>
          </nav>

          <div className="nav-right">
            <div className="lang-toggle" role="group" aria-label="Language">
              <button className={lang === 'en' ? 'active' : ''} onClick={() => setLang('en')}>EN</button>
              <button className={lang === 'es' ? 'active' : ''} onClick={() => setLang('es')}>ES</button>
            </div>
            <a href="tel:+17373547787" className="wa-btn">
              <Icon.WhatsApp size={16} />
              (737) 354-7787
            </a>
            <button className="hamburger" aria-label="Menu" onClick={() => setOpen(true)}>
              <Icon.Menu size={22} />
            </button>
          </div>
        </div>
      </header>

      {/* Mobile menu */}
      <div className={"mobile-menu" + (open ? " open" : "")} role="dialog" aria-modal="true">
        <div className="mobile-menu-head">
          <a href="index.html" className="logo">
            <div className="logo-mark">P&amp;D</div>
            <div className="logo-text">
              <div className="logo-name" style={{ color: "#fff" }}>PROSPEC &amp; DESIGN</div>
              <div className="logo-tag">REMODELING · AUSTIN TX</div>
            </div>
          </a>
          <button className="close-btn" aria-label="Close" onClick={() => setOpen(false)}>
            <Icon.Close size={22} />
          </button>
        </div>
        <nav>
          <a href="index.html">{navT.home}</a>
          <a href="about.html">{navT.about}</a>
          <a href="services.html">{navT.services}</a>
          <div className="submenu">
            {services.map(slug => (
              <a key={slug} href={`service-${slug}.html`}>{(meta[slug] && meta[slug].title) || slug}</a>
            ))}
          </div>
          <a href="projects.html">{navT.projects}</a>
          <a href="blog.html">{navT.blog}</a>
          <a href="contact.html">{navT.contact}</a>
          <a href="quote.html">{navT.quote}</a>
        </nav>
        <div className="mobile-menu-foot">
          <div className="lang-toggle" style={{ alignSelf: "flex-start", borderColor: "rgba(255,255,255,0.2)" }}>
            <button className={lang === 'en' ? 'active' : ''} style={{ color: lang === 'en' ? '#fff' : 'rgba(255,255,255,0.65)' }} onClick={() => setLang('en')}>EN</button>
            <button className={lang === 'es' ? 'active' : ''} style={{ color: lang === 'es' ? '#fff' : 'rgba(255,255,255,0.65)' }} onClick={() => setLang('es')}>ES</button>
          </div>
          <a href="tel:+17373547787" className="wa-btn" style={{ alignSelf: "flex-start" }}>
            <Icon.WhatsApp size={16} /> (737) 354-7787
          </a>
        </div>
      </div>
    </>
  );
};

// =============== PAGE HERO ===============
const PageHero = ({ crumbs = [], eyebrow, titlePre, titleAccent, lead }) => (
  <section className="page-hero">
    <div className="container">
      <div className="crumbs">
        <a href="index.html">Home</a>
        {crumbs.map((c, i) => (
          <React.Fragment key={i}>
            <span className="sep">/</span>
            {c.href
              ? <a href={c.href}>{c.label}</a>
              : <span className="here">{c.label}</span>}
          </React.Fragment>
        ))}
      </div>
      {eyebrow && <div className="eyebrow">{eyebrow}</div>}
      <h1 style={{ marginTop: 14 }}>
        {titlePre} {titleAccent && <span className="green-text">{titleAccent}</span>}
      </h1>
      {lead && <p className="lead">{lead}</p>}
    </div>
  </section>
);

// =============== CTA BANNER ===============
const CTABanner = ({ t }) => {
  const cta = t.cta || { h: "Ready to start your project?", btn: "Get a Free Estimate" };
  return (
    <section className="section section-tight" style={{ paddingBottom: 0 }}>
      <div className="container">
        <div className="cta-banner">
          <h3>{cta.h}</h3>
          <a href="quote.html" className="btn">
            {cta.btn} <Icon.ArrowRight size={16} />
          </a>
        </div>
      </div>
    </section>
  );
};

// =============== FOOTER (multi-page) ===============
const FooterMP = ({ lang, t }) => {
  const fT = t.footer || {};
  const services = window.SERVICE_KEYS;
  const meta = t.services_meta || {};
  return (
    <footer>
      <div className="container">
        <div className="footer-grid">
          <div>
            <a href="index.html" className="logo footer-logo">
              <div className="logo-mark">P&amp;D</div>
              <div className="logo-text">
                <div className="logo-name">PROSPEC &amp; DESIGN</div>
                <div className="logo-tag">REMODELING · AUSTIN TX</div>
              </div>
            </a>
            <p className="footer-about">{fT.about}</p>
            <div className="socials">
              <a href="#" aria-label="Facebook"><Icon.Facebook size={16} /></a>
              <a href="#" aria-label="Instagram"><Icon.Instagram size={16} /></a>
              <a href="#" aria-label="LinkedIn"><Icon.Linkedin size={16} /></a>
              <a href="#" aria-label="Yelp"><Icon.Yelp size={16} /></a>
            </div>
          </div>
          <div>
            <h5>{fT.services_h}</h5>
            <ul>
              {services.map(slug => (
                <li key={slug}>
                  <a href={`service-${slug}.html`}>{(meta[slug] && meta[slug].title) || slug}</a>
                </li>
              ))}
            </ul>
          </div>
          <div>
            <h5>{fT.company_h}</h5>
            <ul>
              {(fT.company_links || []).map((l, i) => (
                <li key={i}><a href={l.href}>{l.label}</a></li>
              ))}
            </ul>
          </div>
          <div>
            <h5>{fT.contact_h}</h5>
            <div className="footer-contact-line"><Icon.Phone size={16} /> (737) 354-7787</div>
            <div className="footer-contact-line"><Icon.Mail size={16} /> help@prospecdesign.com</div>
            <div className="footer-contact-line"><Icon.Pin size={16} /> Austin, Texas</div>
            <div className="footer-contact-line"><Icon.Clock size={16} /> {lang === 'en' ? "Mon – Fri · 8am – 6pm" : "Lun – Vie · 8am – 6pm"}</div>
          </div>
        </div>
        <div className="footer-bottom">
          <div>{fT.copyright}</div>
          <div className="licensed-badge">
            <Icon.Award size={16} /> {fT.licensed}
          </div>
        </div>
      </div>
    </footer>
  );
};

// =============== Service detail body (reusable) ===============
const ServiceDetailBody = ({ slug, t, lang }) => {
  const sd = (t.service_detail || {})[slug];
  if (!sd) return null;
  const heroImgs = {
    'residential':  'https://images.unsplash.com/photo-1600585154340-be6161a56a0c?w=1200&q=80&auto=format&fit=crop',
    'commercial':   'https://images.unsplash.com/photo-1497366216548-37526070297c?w=1200&q=80&auto=format&fit=crop',
    'kitchen':      'https://images.unsplash.com/photo-1556909114-f6e7ad7d3136?w=1200&q=80&auto=format&fit=crop',
    'bathroom':     'https://images.unsplash.com/photo-1552321554-5fefe8c9ef14?w=1200&q=80&auto=format&fit=crop',
    'whole-home':   'https://images.unsplash.com/photo-1600585154526-990dced4db0d?w=1200&q=80&auto=format&fit=crop',
    'carpentry':    'https://images.unsplash.com/photo-1600566753190-17f0baa2a6c3?w=1200&q=80&auto=format&fit=crop',
    'finish':       'https://images.unsplash.com/photo-1600607687939-ce8a6c25118c?w=1200&q=80&auto=format&fit=crop',
    'management':   'https://images.unsplash.com/photo-1581094794329-c8112a89af12?w=1200&q=80&auto=format&fit=crop',
  };
  const galleryImgs = {
    'residential':  ['https://images.unsplash.com/photo-1564013799919-ab600027ffc6?w=700&q=80','https://images.unsplash.com/photo-1600596542815-ffad4c1539a9?w=700&q=80','https://images.unsplash.com/photo-1580587771525-78b9dba3b914?w=700&q=80'],
    'commercial':   ['https://images.unsplash.com/photo-1497366811353-6870744d04b2?w=700&q=80','https://images.unsplash.com/photo-1497366216548-37526070297c?w=700&q=80','https://images.unsplash.com/photo-1486406146926-c627a92ad1ab?w=700&q=80'],
    'kitchen':      ['https://images.unsplash.com/photo-1556909114-f6e7ad7d3136?w=700&q=80','https://images.unsplash.com/photo-1556909190-eccf4a8bf97a?w=700&q=80','https://images.unsplash.com/photo-1565538810643-b5bdb714032a?w=700&q=80'],
    'bathroom':     ['https://images.unsplash.com/photo-1552321554-5fefe8c9ef14?w=700&q=80','https://images.unsplash.com/photo-1620626011761-996317b8d101?w=700&q=80','https://images.unsplash.com/photo-1584622650111-993a426fbf0a?w=700&q=80'],
    'whole-home':   ['https://images.unsplash.com/photo-1600585154340-be6161a56a0c?w=700&q=80','https://images.unsplash.com/photo-1600585154526-990dced4db0d?w=700&q=80','https://images.unsplash.com/photo-1600210492486-724fe5c67fb0?w=700&q=80'],
    'carpentry':    ['https://images.unsplash.com/photo-1600566753190-17f0baa2a6c3?w=700&q=80','https://images.unsplash.com/photo-1616486338812-3dadae4b4ace?w=700&q=80','https://images.unsplash.com/photo-1505691938895-1758d7feb511?w=700&q=80'],
    'finish':       ['https://images.unsplash.com/photo-1600607687939-ce8a6c25118c?w=700&q=80','https://images.unsplash.com/photo-1600566753086-00f18fe6ba53?w=700&q=80','https://images.unsplash.com/photo-1572025442646-866d16c84a54?w=700&q=80'],
    'management':   ['https://images.unsplash.com/photo-1581094794329-c8112a89af12?w=700&q=80','https://images.unsplash.com/photo-1503387762-592deb58ef4e?w=700&q=80','https://images.unsplash.com/photo-1486325212027-8081e485255e?w=700&q=80'],
  };
  return (
    <section className="section">
      <div className="container">
        <div className="service-detail-grid">
          <div className="body">
            <img
              src={heroImgs[slug]}
              alt={sd.title}
              style={{ width: "100%", aspectRatio: "16/9", objectFit: "cover", borderRadius: 24, marginBottom: 32 }}
            />
            <p style={{ fontSize: 19, color: "var(--ink)", fontWeight: 500, lineHeight: 1.6, marginBottom: 32 }}>
              {sd.intro}
            </p>

            <h3>{sd.what_h}</h3>
            <ul>
              {sd.what_list.map((it, i) => <li key={i}>{it}</li>)}
            </ul>

            <h3>{sd.materials_h}</h3>
            <p>{sd.materials_p}</p>

            <div className="gallery-grid">
              {galleryImgs[slug].map((src, i) => (
                <img key={i} src={src + "&auto=format&fit=crop"} alt={`${sd.title} example ${i+1}`} />
              ))}
            </div>

            <h3>{sd.process_h}</h3>
            <div className="process-grid">
              {sd.process.map((p, i) => (
                <div className="process-step" key={i}>
                  <span className="num">STEP {p.step}</span>
                  <h4>{p.h}</h4>
                  <p>{p.p}</p>
                </div>
              ))}
            </div>
          </div>

          <aside className="service-sidebar">
            <h4>{sd.cta}</h4>
            <p>{lang === 'en'
                ? "Tell us about your project and we'll come back with a real estimate within 48 hours."
                : "Cuéntanos sobre tu proyecto y volveremos con una cotización real en menos de 48 horas."}</p>
            <a href="quote.html" className="btn btn-primary">
              {sd.cta} <Icon.ArrowRight size={16} />
            </a>
            <a href="contact.html" className="btn btn-ghost-light" style={{ background: "rgba(255,255,255,0.08)", border: "1px solid rgba(255,255,255,0.18)" }}>
              {lang === 'en' ? "Or contact us" : "O contáctanos"}
            </a>
            <div className="service-sidebar-info">
              <div><Icon.Phone size={16} /> (737) 354-7787</div>
              <div><Icon.Mail size={16} /> help@prospecdesign.com</div>
              <div><Icon.Pin size={16} /> {lang === 'en' ? "Austin metro area" : "Área de Austin"}</div>
              <div><Icon.Clock size={16} /> {lang === 'en' ? "Mon–Fri · 8am–6pm" : "Lun–Vie · 8am–6pm"}</div>
            </div>
          </aside>
        </div>
      </div>
    </section>
  );
};

// Bind to window so each page-specific JSX can use them
Object.assign(window, {
  useLang, mergeT,
  Header, PageHero, CTABanner, FooterMP,
  ServiceDetailBody,
});
