/* Bartal Cohen — v3 */
const { useState, useEffect } = React;

const TWEAKS = /*EDITMODE-BEGIN*/{
  "variant": "ivory",
  "defaultLang": "he",
  "font": "refined"
}/*EDITMODE-END*/;

const SOCIAL = window.SITE_SOCIAL;
const decodeContact = window.decodeContact || ((c) => c);

const BACKDROP_LAYERS = [
  { id: "colonnade", img: "assets/hero-colonnade.svg" },
  { id: "archways",  img: "assets/bg-archways.svg" },
  { id: "pediment",  img: "assets/bg-pediment.svg" },
  { id: "coffers",   img: "assets/bg-coffers.svg" },
];

function Backdrop() {
  return (
    <div className="backdrop-stack" aria-hidden="true">
      {BACKDROP_LAYERS.map(l => (
        <div key={l.id} className="backdrop-layer" data-layer={l.id}
             style={{ backgroundImage: `url("${l.img}")` }} />
      ))}
    </div>
  );
}

const IconX = () => (<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/></svg>);
const IconFb = () => (<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M13.5 21v-7.5h2.5l.5-3h-3V8.75c0-.9.3-1.5 1.6-1.5H17V4.5c-.3 0-1.2-.1-2.3-.1-2.3 0-3.9 1.4-3.9 4v2.1H8v3h2.8V21h2.7z"/></svg>);

function Nav({ t, onToggleLang }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const s = () => setScrolled(window.scrollY > 12);
    window.addEventListener("scroll", s, { passive: true }); s();
    return () => window.removeEventListener("scroll", s);
  }, []);
  return (
    <header className={`nav ${scrolled ? "scrolled" : ""}`}>
      <div className="shell nav-inner">
        <a href="#top" className="brand" aria-label={t.brand.alt}>
          <img src="brand/logo-full-trans.png" alt={t.brand.alt} className="brand-logo dark" />
          <img src="brand/logo-full-light.png" alt="" className="brand-logo light" aria-hidden="true" />
        </a>
        <nav className="nav-links" aria-label="Primary">
          <a href="#firm">{t.nav.firm}</a>
          <a href="#practices">{t.nav.practices}</a>
          <a href="#team">{t.nav.team}</a>
          <a href="#recognition">{t.nav.recognition}</a>
          <a href="#contact">{t.nav.contact}</a>
        </nav>
        <div className="nav-right">
          <div className="nav-social">
            <a href={SOCIAL.twitter} target="_blank" rel="noreferrer noopener" aria-label="X"><IconX/></a>
            <a href={SOCIAL.facebook} target="_blank" rel="noreferrer noopener" aria-label="Facebook"><IconFb/></a>
          </div>
          <button className="lang-toggle" onClick={onToggleLang}>{t.nav.langLabel}</button>
        </div>
      </div>
    </header>
  );
}

function Hero({ t }) {
  return (
    <section id="top" className="hero shell">
      <div>
        <div className="hero-eyebrow t-eyebrow reveal">{t.hero.eyebrow}</div>
        <h1 className="hero-title t-display reveal d1">
          {t.hero.titleA}
          <span className="soft">{t.hero.titleSoft}</span>
        </h1>
      </div>
      <div className="hero-foot reveal d3 t-eyebrow">
        <div className="where">{t.hero.where}</div>
        <div>{t.hero.since}</div>
      </div>
    </section>
  );
}

function Firm({ t }) {
  return (
    <section id="firm" className="section">
      <div className="shell firm">
        <div className="section-head">
          <div className="section-label t-eyebrow reveal">{t.firm.label}</div>
          <h2 className="t-h2 reveal d1">{t.firm.h}</h2>
        </div>
        <p className="t-body-lg reveal d1">{t.firm.p1}</p>
        <p className="t-body-lg reveal d2">{t.firm.p2}</p>
      </div>
    </section>
  );
}

function Practices({ t }) {
  return (
    <section id="practices" className="section">
      <div className="shell">
        <div className="section-head">
          <div className="section-label t-eyebrow reveal">{t.practices.label}</div>
        </div>
        <div className="practice-list">
          {t.practices.items.map((p, i) => (
            <div className="practice-row reveal" style={{ transitionDelay: `${i*80}ms` }} key={i}>
              <div className="p-name">{p.t}</div>
              <div className="p-detail">{p.d}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Team({ t }) {
  return (
    <section id="team" className="section">
      <div className="shell">
        <div className="section-head">
          <div className="section-label t-eyebrow reveal">{t.team.label}</div>
          {t.team.intro && <p className="t-body-lg reveal d1 team-intro">{t.team.intro}</p>}
        </div>
        <div className="team">
          {t.team.items.map((m, i) => (
            <article className="member reveal" style={{ transitionDelay: `${i*100}ms` }} key={i}>
              {m.portrait
                ? <img className="member-portrait photo" src={m.portrait} alt={m.name} />
                : <div className="member-portrait" data-initials={m.initials} aria-hidden="true" />}
              <div className="member-body">
                <h3 className="member-name t-h3">{m.name}</h3>
                <div className="member-role">{m.role}</div>
                {m.tagline && <div className="member-tagline t-eyebrow">{m.tagline}</div>}
                <div className="member-bio">
                  {(Array.isArray(m.bio) ? m.bio : [m.bio]).map((p, j) => (
                    <p className="t-body" key={j}>{p}</p>
                  ))}
                </div>
                <div className="member-contacts">
                  {m.contacts.map((rc, j) => {
                    const c = decodeContact(rc);
                    const isWa = c.href && c.href.includes("wa.me");
                    const isTel = c.href && c.href.startsWith("tel:");
                    const isMail = c.href && c.href.startsWith("mailto:");
                    const icon = isWa ? (
                      <svg viewBox="0 0 24 24" fill="currentColor"><path d="M17.6 14.2c-.3-.2-1.8-.9-2.1-1s-.5-.2-.7.2c-.2.3-.8 1-1 1.2-.2.2-.4.2-.6.1-.3-.2-1.3-.5-2.4-1.5-.9-.8-1.5-1.8-1.7-2.1-.2-.3 0-.5.1-.6.1-.1.3-.4.5-.6.1-.2.2-.3.3-.5.1-.2 0-.4 0-.5-.1-.1-.7-1.7-1-2.3-.2-.6-.5-.5-.7-.5H8c-.2 0-.5.1-.8.4s-1 1-1 2.5 1.1 2.9 1.2 3.1c.1.2 2.1 3.3 5.2 4.7.7.3 1.3.5 1.7.6.7.2 1.4.2 1.9.1.6-.1 1.8-.7 2-1.4.3-.7.3-1.3.2-1.4 0-.1-.3-.2-.6-.3zm-5.6 7.6h0c-1.7 0-3.4-.5-4.9-1.4l-.4-.2-3.7 1 1-3.6-.2-.4A9.7 9.7 0 1 1 12 21.8zM20.3 3.7A11.6 11.6 0 0 0 2 17.4L.4 23.6l6.3-1.7a11.6 11.6 0 0 0 5.5 1.4h0c6.4 0 11.6-5.2 11.6-11.6 0-3.1-1.2-6-3.5-8.1z"/></svg>
                    ) : isTel ? (
                      <svg viewBox="0 0 24 24" fill="currentColor"><path d="M6.6 10.8a15 15 0 0 0 6.6 6.6l2.2-2.2c.3-.3.7-.4 1-.3 1.1.4 2.3.6 3.6.6.6 0 1 .4 1 1V20c0 .6-.4 1-1 1-9.4 0-17-7.6-17-17 0-.6.4-1 1-1h3.5c.6 0 1 .4 1 1 0 1.3.2 2.5.6 3.6.1.4 0 .8-.3 1l-2.2 2.2z"/></svg>
                    ) : isMail ? (
                      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="3" y="5" width="18" height="14" rx="1"/><path d="M3 7l9 6 9-6"/></svg>
                    ) : null;
                    return (
                      <div className={`member-contact ${isWa ? 'whatsapp' : ''}`} key={j}>
                        <div className="mc-k">
                          {icon && <span className="mc-icon" aria-hidden="true">{icon}</span>}
                          <span>{c.k}</span>
                        </div>
                        <div className="mc-v">
                          {c.href ? <a href={c.href} target={c.href.startsWith('http') ? '_blank' : undefined} rel="noreferrer noopener">{c.v}</a> : c.v}
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

function LogoMark({ kind }) {
  if (kind === "bdi") {
    // BdiCode — typographic roundel mark
    return (
      <svg viewBox="0 0 44 44" fill="none" aria-hidden="true">
        <circle cx="22" cy="22" r="20.5" stroke="currentColor" strokeWidth="0.75" fill="none" opacity="0.5"/>
        <text x="22" y="19" textAnchor="middle" fill="currentColor"
              fontFamily="'Cormorant Garamond', Georgia, serif" fontSize="13" fontStyle="italic" fontWeight="500">Bdi</text>
        <line x1="10" y1="23" x2="34" y2="23" stroke="currentColor" strokeWidth="0.5" opacity="0.4"/>
        <text x="22" y="32" textAnchor="middle" fill="currentColor"
              fontFamily="'Inter', sans-serif" fontSize="6" letterSpacing="1.5" fontWeight="500">CODE</text>
      </svg>
    );
  }
  if (kind === "duns") {
    // Duns 100 — monogram numeral mark
    return (
      <svg viewBox="0 0 44 44" fill="none" aria-hidden="true">
        <circle cx="22" cy="22" r="20.5" stroke="currentColor" strokeWidth="0.75" fill="none" opacity="0.5"/>
        <text x="22" y="18" textAnchor="middle" fill="currentColor"
              fontFamily="'Inter', sans-serif" fontSize="6.5" letterSpacing="1.2" fontWeight="500">DUNS</text>
        <text x="22" y="33" textAnchor="middle" fill="currentColor"
              fontFamily="'Cormorant Garamond', Georgia, serif" fontSize="15" fontStyle="italic" fontWeight="500">100</text>
      </svg>
    );
  }
  return null;
}

function Recognition({ t }) {
  return (
    <section id="recognition" className="section">
      <div className="shell">
        <div className="section-head">
          <div className="section-label t-eyebrow reveal">{t.recognition.label}</div>
          <h2 className="t-h2 reveal d1">{t.recognition.h}</h2>
        </div>
        <div className="rec-list">
          {t.recognition.items.map((r, i) => (
            <div className="rec-row reveal" style={{ transitionDelay: `${i*60}ms` }} key={i}>
              <div className="rec-source">
                {r.logo && <span className="rec-logo" aria-hidden="true"><LogoMark kind={r.logo} /></span>}
                <span>{r.src}</span>
              </div>
              <div className="rec-tier">{r.tier}</div>
              <div className="rec-years">{r.years}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Contact({ t }) {
  return (
    <section id="contact" className="section">
      <div className="shell contact-wrap">
        <div className="section-head">
          <div className="section-label t-eyebrow reveal">{t.contact.label}</div>
          <h2 className="t-h2 reveal d1">{t.contact.h}</h2>
        </div>
        <div className="reveal d2">
          {t.contact.blocks.map((rb, i) => {
            const b = decodeContact(rb);
            return (
              <div className="contact-row" key={i}>
                <div className="k">{b.k}</div>
                <div className="v">{b.href ? <a href={b.href}>{b.v}</a> : b.v}</div>
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

function Footer({ t }) {
  return (
    <footer className="footer">
      <div className="shell footer-inner">
        <div>{t.footer.rights}</div>
        <div className="footer-social">
          <a href={SOCIAL.twitter} target="_blank" rel="noreferrer noopener"><IconX/></a>
          <a href={SOCIAL.facebook} target="_blank" rel="noreferrer noopener"><IconFb/></a>
        </div>
        <div>{t.footer.disclaimer}</div>
      </div>
    </footer>
  );
}

function TweaksPanel({ show, variant, setVariant, lang, setLang, font, setFont }) {
  const vars = [
    { id: "ivory", he: "איבורי", en: "Ivory", color: "#d6ccb8" },
    { id: "mono", he: "מונוכרום", en: "Monochrome", color: "#fafaf8" },
    { id: "dark", he: "כהה", en: "Dark", color: "#121210" },
  ];
  const langs = [{ id: "he", he: "עברית", en: "Hebrew" }, { id: "en", he: "אנגלית", en: "English" }];
  const fonts = [
    { id: "refined", he: "מעודן", en: "Refined Serif", hint: "Noto Serif + Cormorant" },
    { id: "editorial", he: "אדיטוריאל", en: "Editorial", hint: "Frank Ruhl + Playfair" },
    { id: "classical", he: "קלאסי", en: "Classical", hint: "David + Libre Caslon" },
    { id: "modern", he: "מודרני", en: "Modern Sans", hint: "Assistant + Inter Tight" },
  ];
  const isHe = lang === "he";
  return (
    <div className={`tweaks ${show ? "show" : ""}`}>
      <h5>{isHe ? "גרסה" : "Variant"}</h5>
      <div className="row">
        {vars.map(v => (
          <button key={v.id} className={`opt ${variant === v.id ? "active" : ""}`} onClick={() => setVariant(v.id)}>
            <span className="swatch" style={{ background: v.color }} />
            <span className="lbl">{isHe ? v.he : v.en}</span>
          </button>
        ))}
      </div>
      <h5>{isHe ? "גופנים" : "Typography"}</h5>
      <div className="row">
        {fonts.map(f => (
          <button key={f.id} className={`opt ${font === f.id ? "active" : ""}`} onClick={() => setFont(f.id)}>
            <span className="lbl">
              <span>{isHe ? f.he : f.en}</span>
              <span className="hint">{f.hint}</span>
            </span>
          </button>
        ))}
      </div>
      <h5>{isHe ? "שפה" : "Language"}</h5>
      <div className="row">
        {langs.map(l => (
          <button key={l.id} className={`opt ${lang === l.id ? "active" : ""}`} onClick={() => setLang(l.id)}>
            <span className="lbl">{isHe ? l.he : l.en}</span>
          </button>
        ))}
      </div>
    </div>
  );
}

function App() {
  const [variant, setVariant] = useState(() => localStorage.getItem("bc_variant") || TWEAKS.variant);
  const [lang, setLang] = useState(() => localStorage.getItem("bc_lang") || TWEAKS.defaultLang);
  const [font, setFont] = useState(() => localStorage.getItem("bc_font") || TWEAKS.font || "refined");
  const [open, setOpen] = useState(false);
  const t = window.SITE_CONTENT[lang];

  useEffect(() => {
    document.documentElement.setAttribute("data-theme", variant);
    document.documentElement.setAttribute("data-font", font);
    document.documentElement.setAttribute("lang", lang);
    document.documentElement.setAttribute("dir", t.dir);
    document.title = t.meta.title;
    localStorage.setItem("bc_variant", variant);
    localStorage.setItem("bc_lang", lang);
    localStorage.setItem("bc_font", font);
  }, [variant, lang, font, t]);

  useEffect(() => {
    const io = new IntersectionObserver((es) => {
      es.forEach(e => { if (e.isIntersecting) { e.target.classList.add("in"); io.unobserve(e.target); } });
    }, { threshold: 0.08, rootMargin: "0px 0px -40px 0px" });
    document.querySelectorAll(".reveal").forEach(el => io.observe(el));
    return () => io.disconnect();
  }, [lang]);

  // Track which section is in view so the fixed backdrop can fade elegantly between pages
  useEffect(() => {
    const sections = document.querySelectorAll("main section[id]");
    if (!sections.length) return;
    const io = new IntersectionObserver((entries) => {
      let top = null, topRatio = 0;
      entries.forEach(e => {
        if (e.isIntersecting && e.intersectionRatio > topRatio) { top = e.target; topRatio = e.intersectionRatio; }
      });
      if (top) document.body.setAttribute("data-active", top.id);
    }, { threshold: [0.25, 0.5, 0.75], rootMargin: "-15% 0px -25% 0px" });
    sections.forEach(s => io.observe(s));
    return () => io.disconnect();
  }, [lang]);

  useEffect(() => {
    const onMsg = (e) => {
      const d = e.data || {};
      if (d.type === "__activate_edit_mode") setOpen(true);
      if (d.type === "__deactivate_edit_mode") setOpen(false);
    };
    window.addEventListener("message", onMsg);
    window.parent.postMessage({ type: "__edit_mode_available" }, "*");

    // Dev shortcut: Cmd/Ctrl + . toggles the Tweaks panel. Ignored while
    // typing in an editable field so it doesn't fight with user input.
    const onKey = (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key === ".") {
        const tag = (e.target && e.target.tagName) || "";
        const editable = /INPUT|TEXTAREA|SELECT/.test(tag) || (e.target && e.target.isContentEditable);
        if (editable) return;
        e.preventDefault();
        setOpen(o => !o);
      }
    };
    window.addEventListener("keydown", onKey);
    return () => {
      window.removeEventListener("message", onMsg);
      window.removeEventListener("keydown", onKey);
    };
  }, []);

  const toggleLang = () => setLang(l => l === "he" ? "en" : "he");
  const setVariantP = (v) => { setVariant(v); window.parent.postMessage({ type: "__edit_mode_set_keys", edits: { variant: v } }, "*"); };
  const setLangP = (l) => { setLang(l); window.parent.postMessage({ type: "__edit_mode_set_keys", edits: { defaultLang: l } }, "*"); };
  const setFontP = (f) => { setFont(f); window.parent.postMessage({ type: "__edit_mode_set_keys", edits: { font: f } }, "*"); };

  return (
    <React.Fragment>
      <Backdrop />
      <Nav t={t} onToggleLang={toggleLang} />
      <main>
        <Hero t={t} />
        <Firm t={t} />
        <Practices t={t} />
        <Team t={t} />
        <Recognition t={t} />
        <Contact t={t} />
      </main>
      <Footer t={t} />
      <TweaksPanel show={open} variant={variant} setVariant={setVariantP} lang={lang} setLang={setLangP} font={font} setFont={setFontP} />
    </React.Fragment>
  );
}

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