/* Shared site infrastructure: i18n, icons, reveal, nav/footer wrappers. */
const DS = window.WarpDesignSystem_e8eaa1;
const { NavBar, Footer, Button, Eyebrow } = DS;

/* ---------- i18n ---------- */
function useLang() {
  const [lang, setLangState] = React.useState(() => localStorage.getItem('hdz-lang') || 'en');
  const setLang = (l) => { localStorage.setItem('hdz-lang', l); setLangState(l); };
  return [lang, setLang];
}

/* ---------- contact facts ---------- */
const HDZ_CONTACT = {
  phone: '(956) 546-4040',
  phoneRaw: '+19565464040',
  fax: '(956) 546-2235',
  email: 'info@hdzlawgrp.com',
  address1: '905 E. Los Ebanos Blvd Ste D',
  address2: 'Brownsville, TX 78520',
};

/* ---------- shared strings ---------- */
const SHARED = {
  nav: {
    en: [
      { label: 'Home', href: 'index.html' },
      { label: 'Personal Injury', href: 'personal-injury.html' },
      { label: 'Criminal Defense', href: 'criminal-defense.html' },
      { label: 'Family Law', href: 'family-law.html' },
      { label: 'Civil Litigation', href: 'civil-litigation.html' },
    ],
    es: [
      { label: 'Inicio', href: 'index.html' },
      { label: 'Lesiones Personales', href: 'personal-injury.html' },
      { label: 'Defensa Criminal', href: 'criminal-defense.html' },
      { label: 'Derecho Familiar', href: 'family-law.html' },
      { label: 'Litigio Civil', href: 'civil-litigation.html' },
    ],
  },
  cta: { en: 'Free Consultation', es: 'Consulta Gratis' },
  footerTagline: {
    en: 'Trial-ready representation for Cameron County and the Rio Grande Valley.',
    es: 'Representación lista para juicio en Brownsville y el Valle del Río Grande.',
  },
  footerPractice: { en: 'Practice Areas', es: 'Áreas de Práctica' },
  footerFirm: { en: 'Firm', es: 'Despacho' },
  footerOffice: { en: 'Office', es: 'Oficina' },
  footerNote: {
    en: 'Attorney Advertising. Prior results do not guarantee a similar outcome.',
    es: 'Publicidad de abogado. Resultados anteriores no garantizan un resultado similar.',
  },
  serving: {
    en: 'Serving Brownsville · Harlingen · McAllen · South Padre Island · San Benito · Los Fresnos · Cameron & Hidalgo Counties',
    es: 'Sirviendo Brownsville · Harlingen · McAllen · South Padre Island · San Benito · Los Fresnos · Condados de Cameron e Hidalgo',
  },
};

/* ---------- icons (minimal 1.5px line) ---------- */
const iconProps = { fill: 'none', stroke: 'currentColor', strokeWidth: 1.5, strokeLinecap: 'round', strokeLinejoin: 'round' };
const Icons = {
  Car: (s = 32) => (<svg width={s} height={s} viewBox="0 0 24 24" {...iconProps}><path d="M19 17h2c.6 0 1-.4 1-1v-3c0-.9-.7-1.7-1.5-1.9C18.7 10.6 16 10 16 10s-1.3-1.4-2.2-2.3c-.5-.4-1.1-.7-1.8-.7H5c-.6 0-1.1.4-1.4.9l-1.4 2.9A3.7 3.7 0 0 0 2 12v4c0 .6.4 1 1 1h2"/><circle cx="7" cy="17" r="2"/><path d="M9 17h6"/><circle cx="17" cy="17" r="2"/></svg>),
  Shield: (s = 32) => (<svg width={s} height={s} viewBox="0 0 24 24" {...iconProps}><path d="M20 13c0 5-3.5 7.5-7.7 9a.6.6 0 0 1-.6 0C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.2-2.7a1.2 1.2 0 0 1 1.6 0C14.5 3.8 17 5 19 5a1 1 0 0 1 1 1z"/></svg>),
  Family: (s = 32) => (<svg width={s} height={s} viewBox="0 0 24 24" {...iconProps}><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>),
  Scale: (s = 32) => (<svg width={s} height={s} viewBox="0 0 24 24" {...iconProps}><path d="M12 3v18"/><path d="M5 7h14"/><path d="M5 7 3 13a3 3 0 0 0 6 0L7 7"/><path d="M17 7l-2 6a3 3 0 0 0 6 0l-2-6"/><path d="M8 21h8"/></svg>),
  Phone: (s = 22) => (<svg width={s} height={s} viewBox="0 0 24 24" {...iconProps}><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.36 1.9.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.34 1.85.57 2.81.7A2 2 0 0 1 22 16.92z"/></svg>),
  Pin: (s = 20) => (<svg width={s} height={s} viewBox="0 0 24 24" {...iconProps}><path d="M20 10c0 6-8 12-8 12s-8-6-8-12a8 8 0 0 1 16 0z"/><circle cx="12" cy="10" r="3"/></svg>),
  Clock: (s = 20) => (<svg width={s} height={s} viewBox="0 0 24 24" {...iconProps}><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg>),
  Globe: (s = 20) => (<svg width={s} height={s} viewBox="0 0 24 24" {...iconProps}><circle cx="12" cy="12" r="10"/><path d="M2 12h20"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>),
  Gavel: (s = 32) => (<svg width={s} height={s} viewBox="0 0 24 24" {...iconProps}><path d="m14 13-7.5 7.5a2.12 2.12 0 0 1-3-3L11 10"/><path d="m16 16 6 6"/><path d="m8 8 6-6"/><path d="m9 7 8 8"/><path d="m21 11-8-8"/></svg>),
};

/* ---------- scroll reveal ---------- */
function Reveal({ children, delay = 0, style }) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const obs = new IntersectionObserver(([entry]) => {
      if (entry.isIntersecting) {
        setTimeout(() => el.classList.add('in'), delay);
        obs.disconnect();
      }
    }, { threshold: 0.15 });
    obs.observe(el);
    return () => obs.disconnect();
  }, []);
  return <div ref={ref} className="reveal" style={style}>{children}</div>;
}

/* ---------- site nav + footer ---------- */
function SiteNav({ lang, setLang, activeHref }) {
  const links = SHARED.nav[lang];
  return (
    <NavBar
      links={links}
      activeHref={activeHref}
      phone={HDZ_CONTACT.phone}
      lang={lang}
      onLangChange={setLang}
      ctaLabel={SHARED.cta[lang]}
      ctaHref="#contact"
      logoSrc="assets/logo.png"
    />
  );
}

function SiteFooter({ lang }) {
  const pa = SHARED.nav[lang].slice(1);
  return (
    <Footer
      logoSrc="assets/logo.png"
      tagline={SHARED.footerTagline[lang]}
      columns={[
        { title: SHARED.footerPractice[lang], items: pa.map((l) => ({ label: l.label, href: l.href })) },
        { title: SHARED.footerFirm[lang], items: [
          { label: lang === 'en' ? 'About the Attorney' : 'Sobre el Abogado', href: 'index.html#attorney' },
          { label: 'FAQ', href: 'index.html#faq' },
          { label: lang === 'en' ? 'Contact' : 'Contacto', href: '#contact' },
        ] },
      ]}
      contact={{
        title: SHARED.footerOffice[lang],
        address1: HDZ_CONTACT.address1,
        address2: HDZ_CONTACT.address2,
        phone: HDZ_CONTACT.phone,
        fax: `Fax ${HDZ_CONTACT.fax}`,
        email: HDZ_CONTACT.email,
      }}
      note={SHARED.footerNote[lang]}
    />
  );
}

function FloatingCall() {
  return (
    <a className="floating-call" href={`tel:${HDZ_CONTACT.phoneRaw}`} aria-label="Call now">
      {Icons.Phone(24)}
    </a>
  );
}

/* ---------- section heading ---------- */
function SectionHeading({ eyebrow, title, align = 'left', maxWidth = '640px' }) {
  return (
    <div style={{ marginBottom: '56px', textAlign: align, ...(align === 'center' ? { marginLeft: 'auto', marginRight: 'auto' } : {}), maxWidth }}>
      <Eyebrow align={align}>{eyebrow}</Eyebrow>
      <h2 style={{ margin: 0, fontSize: 'clamp(32px, 4.5vw, 48px)', lineHeight: 1.12 }}>{title}</h2>
    </div>
  );
}

/* ---------- contact section (shared across pages) ---------- */
function ContactSection({ lang }) {
  const { TextInput, TextArea, SelectField } = DS;
  // Shows the confirmation panel when send.php redirects back with ?sent=1
  const [sent] = React.useState(() => new URLSearchParams(window.location.search).get('sent') === '1');
  const t = {
    eyebrow: { en: 'Contact', es: 'Contacto' },
    title: { en: 'Tell us what happened.', es: 'Cuéntenos qué pasó.' },
    sub: {
      en: 'Your consultation is free and confidential. Evenings and weekends by appointment. Se habla español.',
      es: 'Su consulta es gratuita y confidencial. Noches y fines de semana con cita. We also speak English.',
    },
    name: { en: 'Full name', es: 'Nombre completo' },
    phoneL: { en: 'Phone', es: 'Teléfono' },
    matter: { en: 'Legal matter', es: 'Asunto legal' },
    matters: {
      en: ['Personal Injury', 'Criminal Defense', 'Family Law', 'Civil Litigation', 'Other'],
      es: ['Lesiones Personales', 'Defensa Criminal', 'Derecho Familiar', 'Litigio Civil', 'Otro'],
    },
    msg: { en: 'Tell us about your situation', es: 'Cuéntenos sobre su situación' },
    send: { en: 'Request Free Consultation', es: 'Solicitar Consulta Gratis' },
    sent: {
      en: 'Thank you. We will contact you within one business day. If this is urgent, call (956) 546-4040 now.',
      es: 'Gracias. Le contactaremos dentro de un día hábil. Si es urgente, llame ahora al (956) 546-4040.',
    },
    office: { en: 'Office', es: 'Oficina' },
    hours: { en: 'Hours', es: 'Horario' },
    hoursVal: { en: 'Mon–Fri · 9:00 AM – 5:30 PM', es: 'Lun–Vie · 9:00 AM – 5:30 PM' },
    hoursNote: { en: 'Evenings & weekends by appointment', es: 'Noches y fines de semana con cita' },
    lang: { en: 'Fully bilingual — English & Spanish', es: 'Totalmente bilingüe — inglés y español' },
    emergency: { en: 'Call any time, day or night.', es: 'Llame a cualquier hora, día o noche.' },
  };

  const infoRow = (icon, primary, secondary) => (
    <div style={{ display: 'flex', gap: '16px', alignItems: 'flex-start', padding: '18px 0', borderBottom: '1px solid var(--color-hairline)' }}>
      <span style={{ color: 'var(--color-accent)', flexShrink: 0, paddingTop: '2px' }}>{icon}</span>
      <div>
        <div style={{ color: 'var(--color-ink)', fontSize: '15px', fontWeight: 500 }}>{primary}</div>
        {secondary && <div style={{ color: 'var(--color-mute)', fontSize: '13px', marginTop: '2px' }}>{secondary}</div>}
      </div>
    </div>
  );

  return (
    <section className="section" id="contact">
      <div className="container">
        <SectionHeading eyebrow={t.eyebrow[lang]} title={t.title[lang]} />
        <div className="grid-2" style={{ alignItems: 'start' }}>
          <div>
            <p style={{ margin: '0 0 32px', color: 'var(--color-text)', fontSize: 'var(--text-body-lg-size)', lineHeight: 'var(--text-body-lg-lh)', maxWidth: '480px' }}>
              {t.sub[lang]}
            </p>
            {sent ? (
              <div style={{ border: '1px solid var(--color-hairline-gold)', borderRadius: 'var(--radius-xs)', padding: '32px', color: 'var(--color-ink)', fontSize: '16px', lineHeight: 1.7 }}>
                {t.sent[lang]}
              </div>
            ) : (
              <form action="/send.php" method="post" style={{ display: 'flex', flexDirection: 'column', gap: '18px' }}>
                <div className="form-2col">
                  <TextInput label={t.name[lang]} name="name" required />
                  <TextInput label={t.phoneL[lang]} name="phone" type="tel" required />
                </div>
                <SelectField label={t.matter[lang]} name="matter" options={t.matters[lang]} />
                <TextArea label={t.msg[lang]} name="message" rows={5} />
                <Button variant="gold" type="submit" style={{ alignSelf: 'flex-start' }}>{t.send[lang]}</Button>
              </form>
            )}
          </div>
          <div>
            {infoRow(Icons.Pin(20), HDZ_CONTACT.address1, HDZ_CONTACT.address2)}
            {infoRow(Icons.Phone(20), HDZ_CONTACT.phone, `Fax ${HDZ_CONTACT.fax} · ${HDZ_CONTACT.email}`)}
            {infoRow(Icons.Clock(20), t.hoursVal[lang], t.hoursNote[lang])}
            {infoRow(Icons.Globe(20), t.lang[lang], null)}
            <div style={{ marginTop: '28px', background: 'var(--color-card)', border: '1px solid var(--color-hairline-gold)', borderRadius: 'var(--radius-xs)', padding: '24px', display: 'flex', gap: '16px', alignItems: 'center' }}>
              <span style={{ color: 'var(--color-accent)' }}>{Icons.Phone(26)}</span>
              <div>
                <div style={{ color: 'var(--color-ink)', fontWeight: 600, fontSize: '15px' }}>{t.emergency[lang]}</div>
                <a href={`tel:${HDZ_CONTACT.phoneRaw}`} style={{ color: 'var(--color-accent)', textDecoration: 'none', fontWeight: 700, fontSize: '18px' }}>{HDZ_CONTACT.phone}</a>
              </div>
            </div>
            <iframe
              title="Office map"
              src="https://www.openstreetmap.org/export/embed.html?bbox=-97.5194%2C25.9107%2C-97.4594%2C25.9507&layer=mapnik&marker=25.9307%2C-97.4894"
              style={{ width: '100%', height: '220px', border: '1px solid var(--color-hairline)', borderRadius: 'var(--radius-xs)', marginTop: '28px' }}
              loading="lazy"
            ></iframe>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- CTA band ---------- */
function CTABand({ lang, title, sub }) {
  return (
    <section style={{ background: 'var(--color-bg-soft)', borderTop: '1px solid var(--color-hairline)', borderBottom: '1px solid var(--color-hairline)', padding: '96px 0', textAlign: 'center' }}>
      <div className="container">
        <img src="assets/logo-gold.png" alt="" loading="lazy" style={{ height: '64px', width: 'auto', marginBottom: '28px', opacity: 0.9 }} />
        <h2 style={{ margin: '0 0 16px', fontSize: 'clamp(30px, 4vw, 44px)', lineHeight: 1.15 }}>{title}</h2>
        <p style={{ margin: '0 auto 36px', maxWidth: '560px', color: 'var(--color-text)', fontSize: 'var(--text-body-lg-size)', lineHeight: 'var(--text-body-lg-lh)' }}>{sub}</p>
        <div style={{ display: 'flex', gap: '16px', justifyContent: 'center', flexWrap: 'wrap' }}>
          <Button variant="gold" href="#contact">{SHARED.cta[lang]}</Button>
          <Button variant="outline" href={`tel:${HDZ_CONTACT.phoneRaw}`}>{HDZ_CONTACT.phone}</Button>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, {
  useLang, HDZ_CONTACT, SHARED, Icons, Reveal,
  SiteNav, SiteFooter, FloatingCall, SectionHeading, ContactSection, CTABand,
});
