// ── Helpers ──────────────────────────────────────────────────────────────────
function mapRange(value, fromLow, fromHigh, toLow, toHigh) {
  if (fromLow === fromHigh) return toLow;
  return toLow + ((value - fromLow) / (fromHigh - fromLow)) * (toHigh - toLow);
}

// ── PhotoSlot ─────────────────────────────────────────────────────────────────
function PhotoSlot({ label, ratio = "4/5", tone = "light", src, objectPosition = "center", style = {} }) {
  const bg = tone === "dark"
    ? "repeating-linear-gradient(135deg, #1a1a1a 0 6px, #222 6px 12px)"
    : "repeating-linear-gradient(135deg, #eceae5 0 6px, #f4f2ed 6px 12px)";
  const fg = tone === "dark" ? "rgba(255,255,255,.55)" : "rgba(0,0,0,.5)";
  if (src) {
    return (
      <div style={{ aspectRatio: ratio, background: "#111", position: "relative", overflow: "hidden", ...style }}>
        <img src={src} alt={label} style={{ width: "100%", height: "100%", objectFit: "cover", objectPosition, display: "block" }} />
      </div>
    );
  }
  return (
    <div style={{
      aspectRatio: ratio, background: bg, color: fg,
      fontFamily: "ui-monospace, 'SF Mono', Menlo, monospace",
      fontSize: 10, letterSpacing: 0.5, textTransform: "uppercase",
      display: "flex", alignItems: "flex-end", justifyContent: "flex-start",
      padding: 12, position: "relative", overflow: "hidden", ...style,
    }}>
      <span style={{ background: tone === "dark" ? "rgba(0,0,0,.6)" : "rgba(255,255,255,.85)", padding: "3px 6px" }}>
        [ {label} ]
      </span>
    </div>
  );
}

// ── OrionMark ─────────────────────────────────────────────────────────────────
function OrionMark({ size = 28, color = "#ffffff" }) {
  const isLight = typeof color === "string" && /^#?(f|e|d|c|b|a|9)/i.test(color.replace('#', ''));
  const src = isLight ? "assets/images/logo-light.png" : "assets/images/logo-dark.png";
  return (
    <div style={{ width: size * 0.9, height: size * 0.9, overflow: "hidden", display: "inline-block", position: "relative" }}>
      <img src={src} alt="" style={{
        position: "absolute", height: size * 2.2, width: "auto",
        top: size * -0.2, left: size * -1.3, userSelect: "none",
      }} draggable={false} />
    </div>
  );
}

// ── OrionLogotype ─────────────────────────────────────────────────────────────
function OrionLogotype({ height = 40, color = "#ffffff" }) {
  const isLight = typeof color === "string" && /^#?(f|e|d|c|b|a|9|8)/i.test(color.replace('#', ''));
  const src = isLight ? "assets/images/logo-light.png" : "assets/images/logo-dark.png";
  const width = height * 2.28;
  return (
    <img src={src} alt="Orion Óptica | Relojoaria"
      style={{ height, width, display: "block", userSelect: "none" }}
      draggable={false}
    />
  );
}

// ── Rule ──────────────────────────────────────────────────────────────────────
function Rule({ color = "currentColor", opacity = 1, height = 1, style = {} }) {
  return <div style={{ height, background: color, opacity, width: "100%", ...style }} />;
}

// ── BookingModal ──────────────────────────────────────────────────────────────
function BookingModal({ open, onClose, theme }) {
  const [step, setStep]       = React.useState(1);
  const [service, setService] = React.useState("Exame de vista completo");
  const [date, setDate]       = React.useState(null);
  const [time, setTime]       = React.useState(null);
  const [name, setName]       = React.useState("");
  const [phone, setPhone]     = React.useState("");
  const [done, setDone]       = React.useState(false);

  React.useEffect(() => { if (open) { setStep(1); setDone(false); } }, [open]);
  if (!open) return null;

  const days = [];
  const d = new Date();
  while (days.length < 10) { d.setDate(d.getDate() + 1); if (d.getDay() !== 0) days.push(new Date(d)); }
  const dayLabel   = (d) => ["Dom","Seg","Ter","Qua","Qui","Sex","Sáb"][d.getDay()];
  const monthLabel = (d) => ["jan","fev","mar","abr","mai","jun","jul","ago","set","out","nov","dez"][d.getMonth()];
  const times = ["09:00","10:00","11:00","14:00","15:00","16:00","17:00"];

  const { bg, fg, muted, border, accent, displayFamily, displayWeight } = theme;

  const field = {
    width: "100%", padding: "14px 16px", background: "transparent",
    border: `1px solid ${border}`, color: fg, fontFamily: "inherit",
    fontSize: 15, outline: "none",
  };
  const pill = (active) => ({
    padding: "10px 14px",
    border: `1px solid ${active ? fg : border}`,
    background: active ? fg : "transparent",
    color: active ? bg : fg,
    cursor: "pointer", fontFamily: "inherit", fontSize: 13, letterSpacing: 0.3, transition: "all .15s",
  });
  const submit = () => { setDone(true); setTimeout(() => onClose(), 2200); };

  return (
    <div onClick={onClose} style={{
      position: "fixed", inset: 0, background: "rgba(10,10,10,.6)", backdropFilter: "blur(8px)",
      zIndex: 1000, display: "flex", alignItems: "center", justifyContent: "center", padding: 24,
      animation: "fadeIn .25s ease-out",
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        width: "100%", maxWidth: 560, background: bg, color: fg,
        border: `1px solid ${border}`, animation: "slideUp .3s cubic-bezier(.2,.7,.3,1)",
      }}>
        {done ? (
          <div style={{ padding: "80px 40px", textAlign: "center" }}>
            <div style={{ fontSize: 11, letterSpacing: 3, opacity: .6, marginBottom: 24 }}>CONFIRMADO</div>
            <div style={{ fontFamily: displayFamily, fontSize: 36, lineHeight: 1.1, fontWeight: displayWeight, marginBottom: 16 }}>
              Até {date && dayLabel(date).toLowerCase()}, {name.split(" ")[0]}.
            </div>
            <div style={{ fontSize: 14, opacity: .7 }}>Enviamos os detalhes no {phone}.</div>
          </div>
        ) : (
          <>
            <div style={{ padding: "20px 24px", borderBottom: `1px solid ${border}`, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <div style={{ fontSize: 11, letterSpacing: 3, opacity: .6 }}>AGENDAR · PASSO {step} DE 3</div>
              <button onClick={onClose} style={{ background: "none", border: "none", color: fg, fontSize: 20, cursor: "pointer", opacity: .6, padding: 0 }}>×</button>
            </div>
            <div style={{ padding: "32px 24px 24px" }}>
              {step === 1 && (
                <>
                  <div style={{ fontFamily: displayFamily, fontSize: 28, lineHeight: 1.1, fontWeight: displayWeight, marginBottom: 28 }}>O que precisa hoje?</div>
                  <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                    {["Exame de vista completo", "Ajuste de armação", "Troca de lentes", "Atendimento infantil"].map(s => (
                      <button key={s} onClick={() => setService(s)} style={{
                        padding: "16px 18px", textAlign: "left",
                        border: `1px solid ${service === s ? fg : border}`,
                        background: service === s ? `${fg}08` : "transparent",
                        color: fg, cursor: "pointer", fontFamily: "inherit", fontSize: 15,
                        display: "flex", alignItems: "center", justifyContent: "space-between",
                      }}>
                        {s}
                        <span style={{ opacity: service === s ? 1 : 0, fontSize: 12 }}>●</span>
                      </button>
                    ))}
                  </div>
                </>
              )}
              {step === 2 && (
                <>
                  <div style={{ fontFamily: displayFamily, fontSize: 28, lineHeight: 1.1, fontWeight: displayWeight, marginBottom: 28 }}>Quando fica bom?</div>
                  <div style={{ display: "flex", gap: 6, overflowX: "auto", marginBottom: 24, paddingBottom: 4 }}>
                    {days.map((dt, i) => {
                      const active = date && dt.toDateString() === date.toDateString();
                      return (
                        <button key={i} onClick={() => setDate(dt)} style={{
                          flexShrink: 0, width: 64, padding: "12px 0",
                          border: `1px solid ${active ? fg : border}`,
                          background: active ? fg : "transparent",
                          color: active ? bg : fg, cursor: "pointer", fontFamily: "inherit",
                          display: "flex", flexDirection: "column", gap: 4, alignItems: "center",
                        }}>
                          <span style={{ fontSize: 10, letterSpacing: 1, opacity: .7, textTransform: "uppercase" }}>{dayLabel(dt)}</span>
                          <span style={{ fontSize: 20, fontWeight: 500 }}>{dt.getDate()}</span>
                          <span style={{ fontSize: 10, opacity: .7 }}>{monthLabel(dt)}</span>
                        </button>
                      );
                    })}
                  </div>
                  {date && (
                    <>
                      <div style={{ fontSize: 11, letterSpacing: 2, opacity: .6, marginBottom: 12 }}>HORÁRIO</div>
                      <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
                        {times.map(t => <button key={t} onClick={() => setTime(t)} style={pill(time === t)}>{t}</button>)}
                      </div>
                    </>
                  )}
                </>
              )}
              {step === 3 && (
                <>
                  <div style={{ fontFamily: displayFamily, fontSize: 28, lineHeight: 1.1, fontWeight: displayWeight, marginBottom: 8 }}>Quase lá.</div>
                  <div style={{ fontSize: 14, opacity: .6, marginBottom: 28 }}>
                    {service} · {date && `${dayLabel(date)} ${date.getDate()}/${date.getMonth()+1}`} · {time}
                  </div>
                  <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                    <input style={field} placeholder="Nome completo" value={name} onChange={(e) => setName(e.target.value)} />
                    <input style={field} placeholder="WhatsApp" value={phone} onChange={(e) => setPhone(e.target.value)} />
                  </div>
                </>
              )}
            </div>
            <div style={{ padding: "16px 24px", borderTop: `1px solid ${border}`, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <button onClick={() => step > 1 ? setStep(step - 1) : onClose()} style={{
                background: "none", border: "none", color: fg, cursor: "pointer",
                fontFamily: "inherit", fontSize: 13, letterSpacing: 1, textTransform: "uppercase", opacity: .7,
              }}>
                ← {step > 1 ? "voltar" : "cancelar"}
              </button>
              <button
                disabled={(step === 2 && (!date || !time)) || (step === 3 && (!name || !phone))}
                onClick={() => step === 3 ? submit() : setStep(step + 1)}
                style={{
                  padding: "12px 24px", background: fg, color: bg, border: "none", cursor: "pointer",
                  fontFamily: "inherit", fontSize: 13, letterSpacing: 2, textTransform: "uppercase",
                  opacity: ((step === 2 && (!date || !time)) || (step === 3 && (!name || !phone))) ? .4 : 1,
                }}>
                {step === 3 ? "confirmar →" : "continuar →"}
              </button>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

// ── EtheralShadow ─────────────────────────────────────────────────────────────
function EtheralShadow({ sizing = 'fill', color = 'rgba(244, 242, 237, 1)', animation, noise, style, className }) {
  const idBase = React.useId().replace(/:/g, '');
  const filterId = `shadowoverlay-${idBase}`;
  const animationEnabled = animation && animation.scale > 0;
  const feColorMatrixRef = React.useRef(null);
  const rafRef = React.useRef(null);
  const hueRef = React.useRef(0);

  const displacementScale = animation ? mapRange(animation.scale, 1, 100, 20, 100) : 0;
  const animationDuration = animation ? mapRange(animation.speed, 1, 100, 1000, 50) : 1;

  React.useEffect(() => {
    if (!animationEnabled) return;
    const cycleSecs = animationDuration / 25;
    const degsPerMs = 360 / (cycleSecs * 1000);
    let lastTime = null;
    function tick(timestamp) {
      if (lastTime !== null) {
        hueRef.current = (hueRef.current + degsPerMs * (timestamp - lastTime)) % 360;
        if (feColorMatrixRef.current) feColorMatrixRef.current.setAttribute('values', String(hueRef.current));
      }
      lastTime = timestamp;
      rafRef.current = requestAnimationFrame(tick);
    }
    rafRef.current = requestAnimationFrame(tick);
    return () => { if (rafRef.current) cancelAnimationFrame(rafRef.current); };
  }, [animationEnabled, animationDuration]);

  const baseFreqX = animationEnabled ? mapRange(animation.scale, 0, 100, 0.001, 0.0005) : 0.001;
  const baseFreqY = animationEnabled ? mapRange(animation.scale, 0, 100, 0.004, 0.002) : 0.004;

  return (
    <div className={className} style={{ overflow: 'hidden', position: 'relative', width: '100%', height: '100%', ...style }}>
      <div style={{ position: 'absolute', inset: -displacementScale, filter: animationEnabled ? `url(#${filterId}) blur(4px)` : 'none' }}>
        {animationEnabled && (
          <svg style={{ position: 'absolute', width: 0, height: 0 }}>
            <defs>
              <filter id={filterId}>
                <feTurbulence result="undulation" numOctaves="2" baseFrequency={`${baseFreqX},${baseFreqY}`} seed="0" type="turbulence" />
                <feColorMatrix ref={feColorMatrixRef} in="undulation" type="hueRotate" values="180" />
                <feColorMatrix in="dist" result="circulation" type="matrix" values="4 0 0 0 1  4 0 0 0 1  4 0 0 0 1  1 0 0 0 0" />
                <feDisplacementMap in="SourceGraphic" in2="circulation" scale={displacementScale} result="dist" />
                <feDisplacementMap in="dist" in2="undulation" scale={displacementScale} result="output" />
              </filter>
            </defs>
          </svg>
        )}
        <div style={{
          backgroundColor: color,
          maskImage: `url('https://framerusercontent.com/images/ceBGguIpUU8luwByxuQz79t7To.png')`,
          WebkitMaskImage: `url('https://framerusercontent.com/images/ceBGguIpUU8luwByxuQz79t7To.png')`,
          maskSize: sizing === 'stretch' ? '100% 100%' : 'cover',
          WebkitMaskSize: sizing === 'stretch' ? '100% 100%' : 'cover',
          maskRepeat: 'no-repeat', WebkitMaskRepeat: 'no-repeat',
          maskPosition: 'center', WebkitMaskPosition: 'center',
          width: '100%', height: '100%',
        }} />
      </div>
      {noise && noise.opacity > 0 && (
        <div style={{
          position: 'absolute', inset: 0,
          backgroundImage: `url("https://framerusercontent.com/images/g0QcWrxr87K0ufOxIUFBakwYA8.png")`,
          backgroundSize: noise.scale * 200, backgroundRepeat: 'repeat',
          opacity: noise.opacity / 2,
        }} />
      )}
    </div>
  );
}

// ── GlassesShader ─────────────────────────────────────────────────────────────
function GlassesShader({ style, className }) {
  const canvasRef = React.useRef(null);
  const rafRef    = React.useRef(null);

  const vsSource = `attribute vec4 aPos; void main() { gl_Position = aPos; }`;
  const fsSource = `
    precision highp float;
    uniform vec2  iResolution;
    uniform float iTime;
    float sdSegment(vec2 p, vec2 a, vec2 b) {
      vec2 pa = p - a, ba = b - a;
      float h = clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0);
      return length(pa - ba * h);
    }
    float sdRing(vec2 p, float r, float w) { return abs(length(p) - r) - w; }
    float glow(float d, float r) { return r / (d * d + r + 0.0001); }
    void main() {
      vec2 fc  = gl_FragCoord.xy;
      float mn = min(iResolution.x, iResolution.y);
      vec2 uv  = (fc - 0.5 * iResolution.xy) / mn;
      float t = iTime; float breathe = sin(t * 1.1) * 0.5 + 0.5;
      float r = 0.195; float sep = 0.235; float lw = 0.0035;
      vec2 lc = vec2(-sep, 0.018); vec2 rc = vec2(sep, 0.018);
      float dL = sdRing(uv - lc, r, lw); float dR = sdRing(uv - rc, r, lw);
      vec2 bL = lc + vec2(r * 0.82, 0.0); vec2 bR = rc - vec2(r * 0.82, 0.0);
      vec2 bM = (bL + bR) * 0.5 + vec2(0.0, -0.018);
      float dBr = min(sdSegment(uv, bL, bM) - lw * 0.55, sdSegment(uv, bM, bR) - lw * 0.55);
      vec2 tSL = lc + vec2(-r, 0.0); vec2 tEL = vec2(-0.62, 0.045);
      float dTL = sdSegment(uv, tSL, tEL) - lw * 0.7;
      vec2 tSR = rc + vec2(r, 0.0); vec2 tER = vec2(0.62, 0.045);
      float dTR = sdSegment(uv, tSR, tER) - lw * 0.7;
      float dHL = length(uv - tSL) - lw * 2.2; float dHR = length(uv - tSR) - lw * 2.2;
      float dNL = sdSegment(uv, lc + vec2(r * 0.52, -0.008), lc + vec2(r * 0.42, -0.038)) - lw * 0.5;
      float dNR = sdSegment(uv, rc - vec2(r * 0.52, 0.008), rc - vec2(r * 0.42, 0.038)) - lw * 0.5;
      float d = min(min(min(min(min(min(min(dL, dR), dBr), dTL), dTR), dHL), dHR), min(dNL, dNR));
      float line = smoothstep(0.0028, 0.0, d);
      float g1 = glow(max(d, 0.0005), 0.00015) * 0.35;
      float g2 = glow(max(d, 0.0005), 0.0008)  * 0.22;
      float g3 = glow(max(d, 0.0005), 0.004)   * 0.09;
      float totalGlow = (g1 + g2 + g3) * (0.65 + 0.35 * breathe);
      float sweep = sin(t * 0.9) * 0.55;
      float shimMask = exp(-pow((uv.x - sweep) * 3.8, 2.0));
      float shimmer = shimMask * (line + totalGlow * 0.25) * 0.25;
      float reflL = smoothstep(r + 0.01, r - 0.05, length(uv - lc)) * smoothstep(r - 0.04, r - 0.12, length(uv - lc)) * 0.03 * (0.5 + 0.5 * breathe);
      float reflR = smoothstep(r + 0.01, r - 0.05, length(uv - rc)) * smoothstep(r - 0.04, r - 0.12, length(uv - rc)) * 0.03 * (0.5 + 0.5 * breathe);
      float lensGlow = reflL + reflR;
      vec3 warmLine = vec3(1.00, 0.97, 0.82); vec3 warmGlow = vec3(1.00, 0.86, 0.48);
      vec3 shimColor = vec3(1.00, 1.00, 0.92); vec3 lensColor = vec3(0.95, 0.88, 0.60);
      vec3 bg = vec3(0.035, 0.030, 0.030); vec3 col = bg;
      col += warmGlow * totalGlow; col += warmLine * line * 0.85;
      col += shimColor * shimmer; col += lensColor * lensGlow;
      col = clamp(col, 0.0, 1.0);
      gl_FragColor = vec4(col, 1.0);
    }
  `;

  React.useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const gl = canvas.getContext('webgl');
    if (!gl) return;
    function compile(type, src) {
      const s = gl.createShader(type);
      gl.shaderSource(s, src); gl.compileShader(s);
      if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) { console.error(gl.getShaderInfoLog(s)); return null; }
      return s;
    }
    const prog = gl.createProgram();
    gl.attachShader(prog, compile(gl.VERTEX_SHADER, vsSource));
    gl.attachShader(prog, compile(gl.FRAGMENT_SHADER, fsSource));
    gl.linkProgram(prog);
    const buf = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, buf);
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1,-1,1,-1,-1,1,1,1]), gl.STATIC_DRAW);
    const posLoc = gl.getAttribLocation(prog, 'aPos');
    const resLoc = gl.getUniformLocation(prog, 'iResolution');
    const timLoc = gl.getUniformLocation(prog, 'iTime');
    function resize() {
      const p = canvas.parentElement; if (!p) return;
      canvas.width = p.clientWidth; canvas.height = p.clientHeight;
      gl.viewport(0, 0, canvas.width, canvas.height);
    }
    const ro = new ResizeObserver(resize);
    ro.observe(canvas.parentElement); resize();
    const t0 = Date.now();
    function render() {
      const elapsed = (Date.now() - t0) / 1000;
      gl.clearColor(0,0,0,1); gl.clear(gl.COLOR_BUFFER_BIT);
      gl.useProgram(prog);
      gl.uniform2f(resLoc, canvas.width, canvas.height);
      gl.uniform1f(timLoc, elapsed);
      gl.bindBuffer(gl.ARRAY_BUFFER, buf);
      gl.vertexAttribPointer(posLoc, 2, gl.FLOAT, false, 0, 0);
      gl.enableVertexAttribArray(posLoc);
      gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
      rafRef.current = requestAnimationFrame(render);
    }
    rafRef.current = requestAnimationFrame(render);
    return () => { if (rafRef.current) cancelAnimationFrame(rafRef.current); ro.disconnect(); };
  }, []);

  return <canvas ref={canvasRef} style={{ display: 'block', width: '100%', height: '100%', ...style }} className={className} />;
}

// ── DirectionB ────────────────────────────────────────────────────────────────
function DirectionB({ tweaks = {} }) {
  const { paletteIndex = 0, fontIndex = 0, heroVariant = 0 } = tweaks;

  const palettes = [
    { bg: "#0a0a0a", fg: "#f4f2ed", muted: "rgba(244,242,237,.55)", border: "rgba(244,242,237,.12)", accent: "#f4f2ed", photoTone: "dark" },
    { bg: "#111110", fg: "#eae6dd", muted: "rgba(234,230,221,.5)",  border: "rgba(234,230,221,.1)",  accent: "#c9a97a", photoTone: "dark" },
    { bg: "#0c0d10", fg: "#e8eaef", muted: "rgba(232,234,239,.5)",  border: "rgba(232,234,239,.1)",  accent: "#8aa4c4", photoTone: "dark" },
  ];
  const fonts = [
    { display: "'Neue Haas Grotesk Display Pro', 'Helvetica Neue', Helvetica, Arial, sans-serif", displayWeight: 500, body: "'Helvetica Neue', Helvetica, Arial, sans-serif", mono: "'JetBrains Mono', monospace" },
    { display: "'Archivo', 'Helvetica Neue', sans-serif",      displayWeight: 500, body: "'Archivo', sans-serif",       mono: "'JetBrains Mono', monospace" },
    { display: "'Space Grotesk', 'Helvetica Neue', sans-serif", displayWeight: 500, body: "'Space Grotesk', sans-serif", mono: "'JetBrains Mono', monospace" },
  ];

  const p = palettes[paletteIndex % palettes.length];
  const f = fonts[fontIndex % fonts.length];
  const theme = { bg: p.bg, fg: p.fg, muted: p.muted, border: p.border, accent: p.accent, displayFamily: f.display, displayWeight: f.displayWeight };

  const [showBooking, setShowBooking]     = React.useState(false);
  const [productFilter, setProductFilter] = React.useState("Todos");
  const [hoveredProduct, setHoveredProduct] = React.useState(null);
  const heroWords = ["enxerga", "sorri", "vive", "escolhe", "confia"];
  const [heroWordIndex, setHeroWordIndex] = React.useState(0);

  React.useEffect(() => {
    const id = setTimeout(() => setHeroWordIndex(i => (i + 1) % heroWords.length), 2000);
    return () => clearTimeout(id);
  }, [heroWordIndex]);

  const filteredProducts = productFilter === "Todos"
    ? ORION_DATA.products
    : ORION_DATA.products.filter(pr => pr.cat === productFilter);

  const pageStyle = { background: p.bg, color: p.fg, fontFamily: f.body, fontSize: 13, lineHeight: 1.5, width: "100%", minHeight: "100%", overflow: "hidden" };
  const display   = (size, weight = f.displayWeight) => ({ fontFamily: f.display, fontWeight: weight, fontSize: size, lineHeight: 0.92, letterSpacing: "-0.035em" });
  const eyebrow   = { fontFamily: f.mono, fontSize: 10, letterSpacing: "0.28em", textTransform: "uppercase", color: p.fg, opacity: 0.55 };
  const container = { padding: "0 48px", maxWidth: 1280, margin: "0 auto" };
  const hairline  = (c = p.border) => ({ height: 1, background: c, width: "100%" });

  return (
    <div style={pageStyle}>

      {/* ═══════ NAV ═══════ */}
      <div style={{ position: "relative", zIndex: 10 }}>
        <div style={{ ...container, display: "grid", gridTemplateColumns: "1fr auto 1fr", alignItems: "center", padding: "22px 48px", gap: 40 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <OrionLogotype height={32} color={p.fg} />
          </div>
          <div style={{ display: "flex", gap: 40, justifyContent: "center" }}>
            {["Herança", "Serviços", "Coleção", "Marcas", "Contato"].map((item, i) => (
              <a key={i}
                href={item === "Coleção" ? "colecoes.html" : `#${item}`}
                style={{ fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase", color: p.fg, textDecoration: "none", opacity: 0.75, fontWeight: 400 }}>
                {item}
              </a>
            ))}
          </div>
          <div style={{ display: "flex", gap: 8, justifyContent: "flex-end", alignItems: "center" }}>
            <span style={{ ...eyebrow, fontSize: 10 }}>PT/EN</span>
            <button onClick={() => setShowBooking(true)} style={{
              padding: "10px 18px", background: p.fg, color: p.bg, border: "none",
              fontSize: 10, letterSpacing: "0.25em", textTransform: "uppercase", cursor: "pointer", fontWeight: 600, fontFamily: "inherit",
            }}>Agendar visita</button>
          </div>
        </div>
        <div style={hairline()} />
      </div>

      {/* ═══════ HERO variant 0 ═══════ */}
      {heroVariant === 0 && (
        <section style={{ position: "relative" }}>
          <div style={{ ...container, padding: "80px 48px 0" }}>
            <div style={{ display: "flex", justifyContent: "space-between", ...eyebrow, marginBottom: 64 }}>
              <span>↳ ÓTICA N.º 001</span>
              <span>PIRABEIRABA · JOINVILLE · SC</span>
              <span>26°13′S 48°52′W</span>
              <span>EST. 1993 / 2026</span>
            </div>
            <h1 style={{ ...display(172), margin: 0, textAlign: "center" }}>
              Ótica{" "}
              <span style={{ fontWeight: 300, fontStyle: "italic" }}>Orion</span>
            </h1>
            <div style={{ ...eyebrow, textAlign: "center", marginTop: 28 }}>
              ————— Três décadas na mesma esquina —————
            </div>
            <div style={{ marginTop: 72, display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 16 }}>
              <PhotoSlot label="detalhe · óculos em lâmpada de bancada" ratio="4/5" tone={p.photoTone} />
              <PhotoSlot label="retrato · cliente · luz lateral" ratio="4/5" tone={p.photoTone} src="assets/images/hero-portrait-1.jpg" />
              <PhotoSlot label="detalhe · vitrine · armações alinhadas" ratio="4/5" tone={p.photoTone} />
            </div>
            <div style={{ marginTop: 40, display: "grid", gridTemplateColumns: "1fr auto 1fr", gap: 40, alignItems: "center" }}>
              <div style={{ fontSize: 15, lineHeight: 1.55, maxWidth: 360, opacity: 0.8 }}>
                A ótica de confiança de Pirabeiraba, em Joinville. Lentes premium, atendimento sem pressa, preços sem letra miúda — há trinta e três anos.
              </div>
              <div style={{ display: "flex", gap: 12 }}>
                <button onClick={() => setShowBooking(true)} style={{
                  padding: "18px 32px", background: p.fg, color: p.bg, border: "none", cursor: "pointer",
                  fontSize: 11, letterSpacing: "0.25em", textTransform: "uppercase", fontWeight: 600, fontFamily: "inherit",
                }}>Agendar visita →</button>
                <a href="colecoes.html" style={{
                  padding: "18px 32px", color: p.fg, border: `1px solid ${p.border}`, textDecoration: "none",
                  fontSize: 11, letterSpacing: "0.25em", textTransform: "uppercase", fontWeight: 500,
                }}>Ver coleção →</a>
              </div>
              <div style={{ textAlign: "right", ...eyebrow }}>
                50.000+ clientes ·<br/>12.000+ armações ·<br/>2ª geração
              </div>
            </div>
          </div>
        </section>
      )}

      {/* ═══════ HERO variant 1 ═══════ */}
      {heroVariant === 1 && (
        <section style={{ ...container, padding: "60px 48px 100px" }}>
          <div style={{ display: "grid", gridTemplateColumns: "0.8fr 1.2fr", gap: 48, alignItems: "stretch" }}>
            <div style={{ display: "flex", flexDirection: "column", justifyContent: "space-between", padding: "20px 0" }}>
              <div style={{ ...eyebrow }}>Pirabeiraba · Jlle</div>
              <div>
                <h1 style={{ ...display(112), margin: 0 }}>
                  Cuidar<br />
                  <span style={{ fontWeight: 300, fontStyle: "italic" }}>de quem</span><br />
                  <span style={{ display: "inline-block", position: "relative", overflow: "hidden", verticalAlign: "bottom", height: "1.05em", width: "100%" }}>
                    <span key={heroWordIndex} className="hero-word-enter" style={{ display: "inline-block", fontStyle: "italic", fontWeight: 300 }}>
                      {heroWords[heroWordIndex]}
                    </span>
                  </span>
                  é um ofício.
                </h1>
                <div style={{ marginTop: 40, fontSize: 15, lineHeight: 1.55, maxWidth: 360, opacity: 0.75 }}>
                  Desde 1993, em Pirabeiraba. Lentes, armações e exames — feitos com o tempo que cada olho merece.
                </div>
                <div style={{ marginTop: 32, display: "flex", gap: 12 }}>
                  <button onClick={() => setShowBooking(true)} style={{
                    padding: "16px 28px", background: p.fg, color: p.bg, border: "none", cursor: "pointer",
                    fontSize: 11, letterSpacing: "0.25em", textTransform: "uppercase", fontWeight: 600, fontFamily: "inherit",
                  }}>Agendar →</button>
                </div>
              </div>
              <div style={{ ...eyebrow, display: "flex", justifyContent: "space-between" }}>
                <span>30 anos</span><span>↓ role</span>
              </div>
            </div>
            <PhotoSlot label="retrato · vertical · cliente experimentando armação · luz natural" ratio="3/4" tone={p.photoTone} src="assets/images/hero-portrait-2.jpg" />
          </div>
        </section>
      )}

      {/* ═══════ HERO variant 2 ═══════ */}
      {heroVariant === 2 && (
        <section style={{ position: "relative", overflow: "hidden" }}>
          <div style={{ ...container, padding: "40px 48px 80px" }}>
            <div style={{ ...eyebrow, display: "flex", justifyContent: "space-between", marginBottom: 24 }}>
              <span>Manifesto</span><span>2025</span>
            </div>
            <div style={{ borderTop: `1px solid ${p.fg}`, borderBottom: `1px solid ${p.fg}`, padding: "48px 0" }}>
              <div style={{ ...display(76, 400), maxWidth: 1100 }}>
                Existem óculos. E existem os <span style={{ fontStyle: "italic", fontWeight: 300 }}>seus</span> óculos. A Orion passa trinta e três anos procurando a diferença.
              </div>
            </div>
            <div style={{ marginTop: 48, display: "grid", gridTemplateColumns: "2fr 1fr", gap: 40, alignItems: "end" }}>
              <PhotoSlot label="panorâmica · bancada de trabalho · ferramentas de ajuste" ratio="21/9" tone={p.photoTone} />
              <div style={{ textAlign: "right" }}>
                <button onClick={() => setShowBooking(true)} style={{
                  padding: "18px 32px", background: p.fg, color: p.bg, border: "none", cursor: "pointer",
                  fontSize: 11, letterSpacing: "0.25em", textTransform: "uppercase", fontWeight: 600, fontFamily: "inherit",
                }}>Agendar visita →</button>
                <div style={{ ...eyebrow, marginTop: 20 }}>ou WhatsApp {ORION_DATA.whatsapp}</div>
              </div>
            </div>
          </div>
        </section>
      )}

      {/* ═══════ METRICS ═══════ */}
      <section style={{ borderTop: `1px solid ${p.border}`, borderBottom: `1px solid ${p.border}` }}>
        <div style={{ ...container, padding: "0 48px" }}>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)" }}>
            {ORION_DATA.metrics.map((m, i) => (
              <div key={i} style={{ padding: "32px 24px 32px 0", borderRight: i < 3 ? `1px solid ${p.border}` : "none", paddingLeft: i > 0 ? 32 : 0 }}>
                <div style={{ ...eyebrow, marginBottom: 14 }}>/ 0{i+1}</div>
                <div style={{ ...display(52), marginBottom: 6 }}>{m.num}</div>
                <div style={{ fontSize: 12, opacity: 0.7 }}>{m.label}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* ═══════ HERITAGE ═══════ */}
      <section id="Herança" style={{ ...container, padding: "140px 48px", position: "relative", overflow: "hidden" }}>
        <EtheralShadow color="rgba(244, 242, 237, 1)" sizing="fill" animation={{ scale: 100, speed: 90 }} noise={{ opacity: 1, scale: 1.2 }} style={{ position: "absolute", inset: 0, zIndex: 0 }} />
        <div style={{ display: "grid", gridTemplateColumns: "1fr 2fr", gap: 64, position: "relative", zIndex: 1 }}>
          <div style={{ position: "sticky", top: 32, height: "fit-content" }}>
            <div style={{ ...eyebrow, marginBottom: 20 }}>/ 001 · Herança</div>
            <h2 style={{ ...display(56), margin: 0 }}>
              Trinta e três anos,<br />uma história,<br />
              <span style={{ fontWeight: 300, fontStyle: "italic" }}>zero</span> atalhos.
            </h2>
            <div style={{ marginTop: 40, paddingTop: 32, borderTop: `1px solid ${p.border}` }}>
              <img src="assets/images/logo-light.png" alt="Orion Óptica | Relojoaria"
                style={{ width: "100%", maxWidth: 220, display: "block", opacity: 0.85 }} />
            </div>
          </div>
          <div style={{ borderLeft: `1px solid ${p.border}`, paddingLeft: 48 }}>
            {ORION_DATA.story.map((s, i) => (
              <div key={i} style={{
                display: "grid", gridTemplateColumns: "80px 1fr", gap: 32,
                padding: "32px 0",
                borderBottom: i < ORION_DATA.story.length - 1 ? `1px solid ${p.border}` : "none",
                alignItems: "baseline",
              }}>
                <div style={{ ...eyebrow, fontSize: 12 }}>{s.year}</div>
                <div style={{ fontSize: 18, lineHeight: 1.45, opacity: 0.9 }}>{s.event}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      <div style={hairline()} />

      {/* ═══════ SERVICES ═══════ */}
      <section id="Serviços" style={{ ...container, padding: "140px 48px" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: 56 }}>
          <div>
            <div style={{ ...eyebrow, marginBottom: 16 }}>/ 002 · Serviços</div>
            <h2 style={{ ...display(72), margin: 0 }}>
              Ofícios da<br />
              <span style={{ fontWeight: 300, fontStyle: "italic" }}>casa.</span>
            </h2>
          </div>
          <div style={{ ...eyebrow }}>↳ 06 ITENS</div>
        </div>
        <div style={{ borderTop: `1px solid ${p.fg}` }}>
          {ORION_DATA.services.map((s, i) => (
            <div key={i} style={{
              display: "grid", gridTemplateColumns: "80px 1fr 2fr 80px", gap: 32,
              padding: "32px 0", borderBottom: `1px solid ${p.border}`,
              alignItems: "center", cursor: "pointer", transition: "background .2s",
            }}
              onMouseEnter={(e) => e.currentTarget.style.background = `${p.fg}04`}
              onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
              <div style={{ ...eyebrow, fontSize: 11 }}>{s.n}</div>
              <div style={{ ...display(28, 500) }}>{s.title}</div>
              <div style={{ fontSize: 14, opacity: 0.7, lineHeight: 1.5 }}>{s.note}</div>
              <div style={{ textAlign: "right", fontSize: 16, opacity: 0.5 }}>→</div>
            </div>
          ))}
        </div>
      </section>

      {/* ═══════ MANIFESTO ═══════ */}
      <section style={{ borderTop: `1px solid ${p.border}`, padding: "120px 48px", position: "relative", overflow: "hidden" }}>
        <GlassesShader style={{ position: "absolute", inset: 0, zIndex: 0, opacity: 0.45 }} />
        <div style={{ maxWidth: 1280, margin: "0 auto", position: "relative", zIndex: 1 }}>
          <div style={{ ...eyebrow, marginBottom: 32 }}>/ manifesto</div>
          <div style={{ ...display(88, 400), maxWidth: 1100 }}>
            <span style={{ opacity: 0.35 }}>"</span>Se você saiu daqui enxergando <span style={{ fontWeight: 300, fontStyle: "italic" }}>melhor</span> do que entrou, fizemos o nosso trabalho."
          </div>
          <div style={{ marginTop: 40, display: "flex", alignItems: "center", gap: 14, opacity: 0.7 }}>
            <div style={{ width: 1, height: 32, background: p.fg, opacity: 0.4 }} />
            <div>
              <div style={{ fontSize: 14 }}>Lucas Scott Pecharki</div>
              <div style={{ ...eyebrow, fontSize: 10 }}>2ª geração · optometrista</div>
            </div>
          </div>
        </div>
      </section>

      {/* ═══════ COLLECTION ═══════ */}
      <section id="Coleção" style={{ borderTop: `1px solid ${p.border}`, padding: "140px 48px" }}>
        <div style={{ maxWidth: 1280, margin: "0 auto" }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: 48 }}>
            <div>
              <div style={{ ...eyebrow, marginBottom: 16 }}>/ 003 · Coleção</div>
              <h2 style={{ ...display(72), margin: 0 }}>
                Em <span style={{ fontWeight: 300, fontStyle: "italic" }}>vitrine.</span>
              </h2>
            </div>
            <div style={{ display: "flex", gap: 0, alignItems: "center" }}>
              {["Todos", "Grau", "Sol"].map((c) => (
                <button key={c} onClick={() => setProductFilter(c)} style={{
                  padding: "10px 16px", background: "transparent",
                  color: p.fg, opacity: productFilter === c ? 1 : 0.5,
                  border: "none",
                  borderBottom: `1px solid ${productFilter === c ? p.fg : "transparent"}`,
                  fontSize: 11, letterSpacing: "0.2em", textTransform: "uppercase", cursor: "pointer",
                  fontFamily: f.mono, fontWeight: 400,
                }}>{c}</button>
              ))}
            </div>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 1, background: p.border, border: `1px solid ${p.border}` }}>
            {filteredProducts.map((pr, i) => (
              <div key={i}
                onMouseEnter={() => setHoveredProduct(i)}
                onMouseLeave={() => setHoveredProduct(null)}
                style={{ background: p.bg, padding: 24, cursor: "pointer", transition: "background .2s" }}>
                <PhotoSlot label={pr.name.toLowerCase()} ratio="1/1" tone={p.photoTone} src={pr.photo} objectPosition={pr.objectPosition} />
                <div style={{ marginTop: 16, display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
                  <div>
                    <div style={{ ...eyebrow, fontSize: 9, marginBottom: 6 }}>{pr.cat} · {pr.tag}</div>
                    <div style={{ fontSize: 15, fontWeight: 500 }}>{pr.name}</div>
                  </div>
                  <div style={{ fontFamily: f.mono, fontSize: 11, opacity: 0.7 }}>{pr.price}</div>
                </div>
                <div style={{
                  marginTop: 16, fontSize: 10, letterSpacing: "0.2em", textTransform: "uppercase",
                  opacity: hoveredProduct === i ? 1 : 0.4, transition: "opacity .2s",
                }}>
                  Ver detalhes →
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* ═══════ BRANDS MARQUEE ═══════ */}
      <section id="Marcas" style={{ borderTop: `1px solid ${p.border}`, borderBottom: `1px solid ${p.border}`, padding: "80px 0", overflow: "hidden" }}>
        <div style={{ ...container, padding: "0 48px", marginBottom: 48 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
            <div style={{ ...eyebrow }}>/ 004 · Marcas que levamos a sério</div>
            <div style={{ ...eyebrow, opacity: 0.4 }}>↓ 14 parceiros</div>
          </div>
        </div>
        <div style={{ overflow: "hidden", width: "100%" }}>
          <div className="brands-track" style={{ display: "flex", gap: 72, alignItems: "center", whiteSpace: "nowrap", width: "max-content" }}>
            {[...ORION_DATA.brands, ...ORION_DATA.brands, ...ORION_DATA.brands, ...ORION_DATA.brands].map((b, i) => (
              b.logo ? (
                <div key={i} style={{ flexShrink: 0, height: 52, display: "flex", alignItems: "center" }}>
                  <img src={b.logo} alt={b.name} style={{
                    height: 36, width: "auto", opacity: 0.85,
                    filter: "brightness(0) invert(1)",
                    objectFit: "contain",
                  }} />
                </div>
              ) : (
                <div key={i} style={{ fontFamily: f.display, fontWeight: 400, fontSize: 48, lineHeight: 1.3, opacity: 0.85, flexShrink: 0, letterSpacing: "-0.035em" }}>
                  {b.name}
                </div>
              )
            ))}
          </div>
        </div>
      </section>

      {/* ═══════ INSTAGRAM ═══════ */}
      <section style={{ ...container, padding: "120px 48px" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 32 }}>
          <div>
            <div style={{ ...eyebrow, marginBottom: 12 }}>/ 005 · Diário</div>
            <h2 style={{ fontFamily: f.display, fontWeight: 500, fontSize: 48, lineHeight: 0.92, letterSpacing: "-0.035em", margin: 0 }}>@oticaorion</h2>
          </div>
          <a href="#" style={{ ...eyebrow, color: p.fg, opacity: 1, textDecoration: "underline", textUnderlineOffset: 4 }}>
            Seguir no Instagram →
          </a>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(6, 1fr)", gap: 4 }}>
          {Array.from({ length: 6 }).map((_, i) => (
            <PhotoSlot key={i} label={`post ${i+1}`} ratio="1/1" tone={p.photoTone} />
          ))}
        </div>
      </section>

      {/* ═══════ CONTACT ═══════ */}
      <section id="Contato" style={{ borderTop: `1px solid ${p.border}`, padding: "120px 48px" }}>
        <div style={{ maxWidth: 1280, margin: "0 auto" }}>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 80 }}>
            <div>
              <div style={{ ...eyebrow, marginBottom: 20 }}>/ 006 · Contato</div>
              <h2 style={{ ...display(88), margin: 0 }}>
                Venha nos<br />
                <span style={{ fontWeight: 300, fontStyle: "italic" }}>visitar.</span>
              </h2>
              <div style={{ marginTop: 40, maxWidth: 470 }}>
                {ORION_DATA.stores.map((s, i) => (
                  <div key={i} style={{
                    padding: "20px 0",
                    borderTop: `1px solid ${p.border}`,
                    borderBottom: i === ORION_DATA.stores.length - 1 ? `1px solid ${p.border}` : "none",
                  }}>
                    <div style={{ display: "flex", alignItems: "baseline", gap: 10, marginBottom: 8 }}>
                      <span style={{ fontSize: 17, fontWeight: 600 }}>{s.name}</span>
                      {s.since && <span style={{ ...eyebrow, fontSize: 10, opacity: 0.55 }}>{s.since}</span>}
                    </div>
                    <div style={{ fontSize: 15, lineHeight: 1.5, opacity: 0.8 }}>{s.address}</div>
                    <div style={{ fontSize: 15, marginTop: 6, opacity: 0.8 }}>{s.phone}</div>
                    <div style={{ ...eyebrow, fontSize: 9.5, marginTop: 10, opacity: 0.5, letterSpacing: "0.16em" }}>
                      {s.razao_social} · CNPJ {s.cnpj}
                    </div>
                  </div>
                ))}
              </div>
              <div style={{ marginTop: 40, display: "flex", gap: 12 }}>
                <a href={`https://wa.me/${ORION_DATA.whatsapp_e164}`} style={{
                  padding: "16px 28px", background: p.fg, color: p.bg, textDecoration: "none",
                  fontSize: 11, letterSpacing: "0.25em", textTransform: "uppercase", fontWeight: 600,
                }}>WhatsApp →</a>
                <button onClick={() => setShowBooking(true)} style={{
                  padding: "16px 28px", background: "transparent", color: p.fg, border: `1px solid ${p.fg}`,
                  fontSize: 11, letterSpacing: "0.25em", textTransform: "uppercase", cursor: "pointer",
                  fontFamily: "inherit", fontWeight: 500,
                }}>Agendar →</button>
              </div>
            </div>
            <div>
              <div style={{ ...eyebrow, marginBottom: 24 }}>↳ Horário</div>
              <div style={{ borderTop: `1px solid ${p.border}` }}>
                {ORION_DATA.hours.map((h, i) => (
                  <div key={i} style={{
                    display: "flex", justifyContent: "space-between", padding: "18px 0",
                    borderBottom: `1px solid ${p.border}`, fontSize: 18, fontWeight: 500,
                  }}>
                    <span>{h.d}</span>
                    <span style={{ opacity: 0.7 }}>{h.h}</span>
                  </div>
                ))}
              </div>
              <div style={{ marginTop: 32 }}>
                <div style={{ ...eyebrow, marginBottom: 6 }}>WhatsApp</div>
                <div style={{ fontSize: 18, fontWeight: 500 }}>{ORION_DATA.whatsapp}</div>
              </div>
            </div>
          </div>
          <div style={{ marginTop: 96, paddingTop: 32, borderTop: `1px solid ${p.border}`, display: "flex", justifyContent: "space-between", alignItems: "flex-end", gap: 32, flexWrap: "wrap" }}>
            <OrionLogotype height={28} color={p.fg} />
            <div style={{ ...eyebrow, fontSize: 10, textAlign: "right", lineHeight: 2 }}>
              {ORION_DATA.company.razao_social} · CNPJ {ORION_DATA.company.cnpj}<br />
              © 2026 · Joinville · Santa Catarina
            </div>
          </div>
        </div>
      </section>

      <BookingModal open={showBooking} onClose={() => setShowBooking(false)} theme={theme} />
    </div>
  );
}

// ── App ───────────────────────────────────────────────────────────────────────
function App() {
  return <DirectionB tweaks={{ paletteIndex: 0, fontIndex: 0, heroVariant: 1 }} />;
}

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