// Brown Ocean — shared components

const { useState, useEffect, useRef } = React;

// -------------------- Wordmark (stacked Brown / Ocean per supplied logo) --------------------
function Wordmark({ size = 20, light = false }) {
  return (
    <div className="wordmark-stack" style={{
      color: light ? "var(--sand-100)" : "var(--brown-900)",
      display: "inline-flex", flexDirection: "column",
      lineHeight: 0.92, letterSpacing: "0.02em"
    }}>
      <span style={{
        fontFamily: "var(--serif)", fontWeight: 500, fontStyle: "normal",
        fontSize: size * 1.35
      }}>Brown</span>
      <span style={{
        fontFamily: "var(--serif)", fontWeight: 500, fontStyle: "italic",
        fontSize: size * 1.35,
        color: light ? "var(--gold)" : "var(--brown-700)",
        marginTop: -2
      }}>Ocean</span>
    </div>
  );
}

// -------------------- Header --------------------
function Header({ route, onNavigate, onQuote }) {
  const [shrunk, setShrunk] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);

  useEffect(() => {
    const onScroll = () => setShrunk(window.scrollY > 40);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  useEffect(() => {
    document.body.style.overflow = menuOpen ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [menuOpen]);

  const links = [
    { id: "home",     label: "Home" },
    { id: "products", label: "Products" },
    { id: "process",  label: "Process" },
    { id: "exports",  label: "Exports" },
    { id: "contact",  label: "Contact" }
  ];

  const handleNavigate = (id) => { onNavigate(id); setMenuOpen(false); };

  return (
    <>
      <header style={{
        position: "sticky", top: 0, zIndex: 50,
        background: shrunk ? "rgba(255, 255, 255, 0.94)" : "transparent",
        backdropFilter: shrunk ? "saturate(140%) blur(14px)" : "none",
        WebkitBackdropFilter: shrunk ? "saturate(140%) blur(14px)" : "none",
        borderBottom: shrunk ? "1px solid var(--line-soft)" : "1px solid transparent",
        transition: "background 0.25s ease, border-color 0.25s ease, padding 0.25s ease, backdrop-filter 0.25s ease",
        padding: shrunk ? "10px 0" : "20px 0"
      }}>
        <div className="container" style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
          <a href="/" onClick={(e) => { e.preventDefault(); handleNavigate("home"); }}
            style={{ display: "flex", alignItems: "center" }}>
            <img
              src="assets/logo.svg"
              alt="Brown Ocean Exports"
              style={{
                height: shrunk ? 46 : 46,
                width: "auto",
                transition: "height 0.25s ease",
                filter: !shrunk ? "drop-shadow(0 1px 3px rgba(0,0,0,0.4))" : "none"
              }}
            />
          </a>
          <nav className="nav-desktop">
            {links.map(l => {
              const active = route === l.id;
              const onDark = !shrunk;
              const baseColor = onDark
                ? (active ? "var(--sand-100)" : "rgba(245, 232, 216, 0.88)")
                : (active ? "var(--brown-900)" : "var(--ink-soft)");
              const borderColor = onDark
                ? (active ? "var(--gold)" : "transparent")
                : (active ? "var(--brown-900)" : "transparent");
              return (
                <a key={l.id} href={l.id === "home" ? "/" : `/${l.id}`}
                  onClick={(e) => { e.preventDefault(); handleNavigate(l.id); }}
                  style={{
                    fontSize: 13, fontWeight: 500, letterSpacing: "0.04em",
                    color: baseColor,
                    borderBottom: `1px solid ${borderColor}`,
                    paddingBottom: 2,
                    transition: "color 0.15s ease, border-color 0.15s ease"
                  }}>
                  {l.label}
                </a>
              );
            })}
            <button
              className={shrunk ? "btn btn-primary" : "btn btn-gold"}
              onClick={onQuote}
              style={{ padding: "10px 18px", fontSize: 13 }}>
              Request Export Quote →
            </button>
          </nav>
          <button
            className="nav-hamburger"
            onClick={() => setMenuOpen(!menuOpen)}
            aria-label={menuOpen ? "Close menu" : "Open menu"}
            style={{
              color: shrunk ? "var(--brown-800)" : "var(--sand-100)",
              border: `1px solid ${shrunk ? "var(--line)" : "rgba(245, 232, 216, 0.4)"}`,
              background: "none"
            }}>
            {menuOpen ? "✕" : "☰"}
          </button>
        </div>
      </header>

      {menuOpen && (
        <div style={{
          position: "fixed", inset: 0, zIndex: 49,
          background: "rgba(255, 255, 255, 0.97)",
          backdropFilter: "blur(20px)", WebkitBackdropFilter: "blur(20px)",
          display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
          gap: 4
        }}>
          {links.map(l => (
            <a key={l.id} href={l.id === "home" ? "/" : `/${l.id}`}
              onClick={(e) => { e.preventDefault(); handleNavigate(l.id); }}
              style={{
                fontSize: 28, fontFamily: "var(--serif)", fontWeight: 500,
                color: route === l.id ? "var(--brown-900)" : "var(--ink-soft)",
                padding: "14px 40px",
                letterSpacing: "-0.01em",
                width: "100%", textAlign: "center",
                borderBottom: route === l.id ? "2px solid var(--gold)" : "2px solid transparent"
              }}>
              {l.label}
            </a>
          ))}
          <button className="btn btn-primary" onClick={() => { onQuote(); setMenuOpen(false); }}
            style={{ marginTop: 32, padding: "14px 32px", fontSize: 16 }}>
            Request Export Quote →
          </button>
        </div>
      )}
    </>
  );
}

// -------------------- Footer --------------------
function Footer({ onNavigate, onQuote }) {
  return (
    <footer className="footer-outer" style={{
      background: "var(--brown-900)",
      color: "var(--sand-200)"
    }}>
      <div className="container">
        <div className="footer-grid">
          <div>
            <div style={{
              display: "inline-block",
              background: "#fff",
              borderRadius: 10,
              padding: "8px 14px"
            }}>
              <img
                src="assets/logo.svg"
                alt="Brown Ocean Exports"
                style={{ height: 40, width: "auto", display: "block" }}
              />
            </div>
            <p style={{ marginTop: 28, maxWidth: 360, color: "var(--sand-300)", fontSize: 15, lineHeight: 1.6 }}>
              Premium makhana sourced from Bihar's Purnia and Katihar wetlands and shipped, traceable, to the world's better grocers.
            </p>
            <button className="btn btn-gold" onClick={onQuote} style={{ marginTop: 28 }}>
              Request Export Quote →
            </button>
          </div>
          <FooterCol title="Product" items={[
            { label: "Raw & Bulk", to: "products" },
            { label: "Roasted Range", to: "products" },
            { label: "Flavours", to: "products" },
            { label: "Specifications", to: "products" }
          ]} onNavigate={onNavigate} />
          <FooterCol title="Company" items={[
            { label: "Origin Story", to: "home" },
            { label: "Process", to: "process" },
            { label: "Certifications", to: "process" },
            { label: "Export Markets", to: "exports" }
          ]} onNavigate={onNavigate} />
          <div>
            <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--sand-400)", marginBottom: 18 }}>
              Get in touch
            </div>
            <div style={{ fontSize: 14, lineHeight: 1.9, color: "var(--sand-200)" }}>
              <div>Ascendance Agro Pvt Ltd</div>
              <div style={{ color: "var(--sand-400)" }}>201, Balakrishna Centre, N.G. Acarya Marg</div>
              <div style={{ color: "var(--sand-400)" }}>Chembur, Mumbai 400071</div>
              <div style={{ marginTop: 12 }}>+91 91364 79617</div>
              <div>vishal@ascendanceagro.com</div>
            </div>
            <div style={{ marginTop: 20, display: "flex", gap: 10 }}>
              {[
                {
                  href: "https://www.linkedin.com/company/ascendance-agro-private-limited/",
                  title: "LinkedIn",
                  hoverColor: "#0A66C2",
                  icon: <path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433a2.062 2.062 0 01-2.063-2.065 2.064 2.064 0 112.063 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z"/>
                }
              ].map(s => (
                <a key={s.title} href={s.href} target="_blank" rel="noopener noreferrer" title={s.title}
                  style={{
                    display: "flex", alignItems: "center", justifyContent: "center",
                    width: 36, height: 36, borderRadius: 8,
                    background: "rgba(255,255,255,0.07)",
                    border: "1px solid rgba(255,255,255,0.1)",
                    color: "var(--sand-400)",
                    transition: "background 0.15s, color 0.15s, border-color 0.15s"
                  }}
                  onMouseEnter={e => { e.currentTarget.style.background = s.hoverColor; e.currentTarget.style.color = "#fff"; e.currentTarget.style.borderColor = s.hoverColor; }}
                  onMouseLeave={e => { e.currentTarget.style.background = "rgba(255,255,255,0.07)"; e.currentTarget.style.color = "var(--sand-400)"; e.currentTarget.style.borderColor = "rgba(255,255,255,0.1)"; }}>
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">{s.icon}</svg>
                </a>
              ))}
            </div>
          </div>
        </div>
        <div style={{
          marginTop: 64, paddingTop: 24,
          borderTop: "1px solid rgba(245, 232, 216, 0.12)",
          display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 12,
          fontSize: 12, color: "var(--sand-400)"
        }}>
          <span className="mono">© MMXXVI Ascendance Agro Pvt Ltd · All rights reserved</span>
          <span className="mono">FSSAI · APEDA · ZED · RCMC</span>
        </div>
      </div>
    </footer>
  );
}
function FooterCol({ title, items, onNavigate }) {
  return (
    <div>
      <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--sand-400)", marginBottom: 18 }}>
        {title}
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        {items.map(it => (
          <a key={it.label} href={it.to === "home" ? "/" : `/${it.to}`}
            onClick={(e) => { e.preventDefault(); onNavigate(it.to); }}
            style={{ fontSize: 14, color: "var(--sand-200)", transition: "color 0.15s" }}
            onMouseEnter={(e) => e.currentTarget.style.color = "var(--gold)"}
            onMouseLeave={(e) => e.currentTarget.style.color = "var(--sand-200)"}>
            {it.label}
          </a>
        ))}
      </div>
    </div>
  );
}

// -------------------- Floating leaves --------------------
function LeafSVG({ size = 36, color = "#6BA368", opacity = 0.5 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 64 64" fill="none" style={{ opacity }}>
      <path d="M8 56 C 8 28, 28 8, 56 8 C 56 36, 36 56, 8 56 Z" fill={color} />
      <path d="M8 56 L 56 8" stroke="rgba(0,0,0,0.18)" strokeWidth="1" />
      <path d="M16 48 L 48 16 M22 50 L 32 30 M14 42 L 30 38 M50 22 L 42 32 M42 14 L 38 30" stroke="rgba(0,0,0,0.12)" strokeWidth="0.7" />
    </svg>
  );
}
function FloatingLeaves({ show, density = 6 }) {
  if (!show) return null;
  const leaves = [
    { top: "8%",  left: "4%",  size: 42, rot: -22, delay: 0,  c: "#6BA368", o: 0.42 },
    { top: "18%", right: "6%", size: 32, rot: 28,  delay: 1.2, c: "#7AAF7A", o: 0.38 },
    { top: "62%", left: "2%",  size: 48, rot: 12,  delay: 2.5, c: "#4F7A4D", o: 0.35 },
    { top: "78%", right: "4%", size: 28, rot: -18, delay: 0.8, c: "#6BA368", o: 0.45 },
    { top: "42%", left: "92%", size: 36, rot: 35,  delay: 3.1, c: "#94B97E", o: 0.30 },
    { top: "92%", left: "44%", size: 24, rot: -8,  delay: 1.6, c: "#6BA368", o: 0.40 }
  ].slice(0, density);
  return (
    <div style={{ position: "absolute", inset: 0, pointerEvents: "none", overflow: "hidden", zIndex: 2 }}>
      {leaves.map((l, i) => (
        <div key={i} className="leaf" style={{
          top: l.top, left: l.left, right: l.right,
          "--r": `${l.rot}deg`, animationDelay: `${l.delay}s`,
          transform: `rotate(${l.rot}deg)`
        }}>
          <LeafSVG size={l.size} color={l.c} opacity={l.o} />
        </div>
      ))}
    </div>
  );
}

// -------------------- Reveal-on-scroll --------------------
function Reveal({ children, delay = 0, as: Tag = "div", ...rest }) {
  const ref = useRef(null);
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) { setVisible(true); io.disconnect(); } });
    }, { threshold: 0.15 });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return (
    <Tag ref={ref} className={`reveal ${visible ? "in" : ""}`} style={{ animationDelay: `${delay}s` }} {...rest}>
      {children}
    </Tag>
  );
}

// -------------------- Section header --------------------
function SectionHeader({ eyebrow, title, italic, body, align = "left", light = false }) {
  return (
    <div style={{ textAlign: align, maxWidth: align === "center" ? 760 : 760, margin: align === "center" ? "0 auto" : undefined }}>
      {eyebrow && <div className="eyebrow" style={{ marginBottom: 16, color: light ? "var(--sand-400)" : undefined }}>{eyebrow}</div>}
      <h2 className="display" style={{
        fontSize: "clamp(40px, 5vw, 68px)",
        margin: 0,
        color: light ? "var(--sand-100)" : "var(--brown-900)"
      }}>
        {title}
        {italic && <> <span className="display-italic" style={{ color: light ? "var(--gold)" : "var(--brown-600)" }}>{italic}</span></>}
      </h2>
      {body && (
        <p style={{
          marginTop: 24, fontSize: 18, lineHeight: 1.6, maxWidth: 620,
          margin: align === "center" ? "24px auto 0" : "24px 0 0",
          color: light ? "var(--sand-300)" : "var(--ink-soft)"
        }}>
          {body}
        </p>
      )}
    </div>
  );
}

// -------------------- Image placeholder (monospace, striped) --------------------
function Placeholder({ label, ratio = "4 / 5", radius = "var(--radius-lg)", tone = "sand", caption, children, style = {} }) {
  const tones = {
    sand:  { bg: "var(--sand-200)",   stripe: "rgba(74, 44, 29, 0.06)", text: "var(--brown-600)" },
    cream: { bg: "var(--sand-100)",   stripe: "rgba(74, 44, 29, 0.05)", text: "var(--brown-700)" },
    dark:  { bg: "var(--brown-700)",  stripe: "rgba(245, 232, 216, 0.06)", text: "var(--sand-300)" },
    gold:  { bg: "#E8D29A",           stripe: "rgba(74, 44, 29, 0.08)", text: "var(--brown-800)" },
    leaf:  { bg: "#D8E5C8",           stripe: "rgba(74, 44, 29, 0.06)", text: "var(--leaf-dark)" }
  };
  const t = tones[tone] || tones.sand;
  return (
    <figure style={{ margin: 0, position: "relative" }}>
      <div style={{
        aspectRatio: ratio,
        borderRadius: radius,
        overflow: "hidden",
        background: t.bg,
        backgroundImage: `repeating-linear-gradient(-30deg, transparent 0 14px, ${t.stripe} 14px 15px)`,
        boxShadow: "var(--shadow-md)",
        display: "flex", alignItems: "center", justifyContent: "center",
        position: "relative",
        ...style
      }}>
        {children}
        {label && (
          <div style={{ textAlign: "center", padding: 24, position: "relative", zIndex: 2 }}>
            <div className="mono" style={{
              color: t.text,
              fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase"
            }}>
              ↳ {label}
            </div>
          </div>
        )}
      </div>
      {caption && (
        <figcaption className="mono" style={{ marginTop: 10, color: "var(--brown-600)" }}>{caption}</figcaption>
      )}
    </figure>
  );
}
// keep ImageFrame as alias for back-compat — if src given, render real photo
function ImageFrame({ alt, ratio = "4 / 5", radius = "var(--radius-lg)", caption, src, ...rest }) {
  if (!src) return <Placeholder label={alt} ratio={ratio} caption={caption} {...rest} />;
  return (
    <figure style={{ margin: 0, position: "relative" }}>
      <div style={{
        aspectRatio: ratio,
        borderRadius: radius,
        overflow: "hidden",
        boxShadow: "var(--shadow-md)",
        background: "var(--sand-200)"
      }}>
        <img src={src} alt={alt}
          loading="lazy"
          style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }} />
      </div>
      {caption && (
        <figcaption className="mono" style={{ marginTop: 10, color: "var(--brown-600)" }}>{caption}</figcaption>
      )}
    </figure>
  );
}

// -------------------- Quote modal --------------------
function QuoteModal({ open, onClose, initialProduct }) {
  const [step, setStep] = useState(0);
  const [data, setData] = useState({
    product: initialProduct || "",
    quantity: "",
    country: "",
    name: "",
    company: "",
    email: "",
    phone: "",
    notes: ""
  });
  const [submitted, setSubmitted] = useState(false);

  useEffect(() => {
    if (open) { setStep(0); setSubmitted(false); }
    if (open) { document.body.style.overflow = "hidden"; }
    else { document.body.style.overflow = ""; }
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  useEffect(() => {
    if (initialProduct) setData(d => ({ ...d, product: initialProduct }));
  }, [initialProduct]);

  if (!open) return null;

  const set = (k, v) => setData(d => ({ ...d, [k]: v }));
  const next = () => setStep(s => Math.min(s + 1, 2));
  const back = () => setStep(s => Math.max(s - 1, 0));
  const canNext = (() => {
    if (step === 0) return data.product && data.quantity;
    if (step === 1) return data.country;
    if (step === 2) return data.name && data.email;
    return true;
  })();

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal-card" onClick={e => e.stopPropagation()}>
        {submitted ? (
          <div style={{ padding: "64px 56px", textAlign: "center" }}>
            <div style={{
              width: 64, height: 64, margin: "0 auto 24px",
              borderRadius: "50%", background: "var(--leaf)",
              display: "flex", alignItems: "center", justifyContent: "center",
              color: "white", fontSize: 28
            }}>✓</div>
            <h3 className="display" style={{ fontSize: 36, margin: 0, color: "var(--brown-900)" }}>
              Quote received.
            </h3>
            <p style={{ marginTop: 16, color: "var(--ink-soft)", fontSize: 16 }}>
              Our export team will reach you within one business day at <strong>{data.email}</strong>.
            </p>
            <button className="btn btn-primary" onClick={onClose} style={{ marginTop: 32 }}>
              Close
            </button>
          </div>
        ) : (
          <div style={{ padding: "40px 48px 48px" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 24 }}>
              <div>
                <div className="eyebrow">Step {step + 1} / 3</div>
                <h3 className="display" style={{ fontSize: 32, margin: "8px 0 0", color: "var(--brown-900)" }}>
                  {step === 0 && <>Tell us what <span className="display-italic" style={{ color: "var(--brown-600)" }}>you need.</span></>}
                  {step === 1 && <>Where is it <span className="display-italic" style={{ color: "var(--brown-600)" }}>shipping?</span></>}
                  {step === 2 && <>How do we <span className="display-italic" style={{ color: "var(--brown-600)" }}>reach you?</span></>}
                </h3>
              </div>
              <button onClick={onClose} aria-label="Close"
                style={{ width: 36, height: 36, borderRadius: "50%", border: "1px solid var(--line)", color: "var(--brown-700)" }}>
                ✕
              </button>
            </div>

            {/* progress */}
            <div style={{ display: "flex", gap: 6, marginBottom: 32 }}>
              {[0, 1, 2].map(i => (
                <div key={i} style={{
                  flex: 1, height: 3, borderRadius: 999,
                  background: i <= step ? "var(--brown-700)" : "var(--line-soft)",
                  transition: "background 0.3s ease"
                }} />
              ))}
            </div>

            {step === 0 && (
              <div style={{ display: "grid", gap: 20 }}>
                <div>
                  <label>Product</label>
                  <select value={data.product} onChange={e => set("product", e.target.value)}>
                    <option value="">Select a product or category</option>
                    <optgroup label="Categories">
                      <option value="raw">Raw & Bulk Supply (15-24 mm)</option>
                      <option value="roasted">Roasted & Flavoured (full range)</option>
                    </optgroup>
                    <optgroup label="Flavours">
                      {FLAVOURS.map(f => <option key={f.id} value={f.id}>{f.name}</option>)}
                    </optgroup>
                    <option value="private-label">Private-label programme</option>
                  </select>
                </div>
                <div>
                  <label>Estimated quantity</label>
                  <select value={data.quantity} onChange={e => set("quantity", e.target.value)}>
                    <option value="">Select volume</option>
                    <option>Trial — 1 ton / 500 cartons</option>
                    <option>Small — 1–5 tons / month</option>
                    <option>Medium — 5–20 tons / month</option>
                    <option>FCL programme — 20+ tons / month</option>
                  </select>
                </div>
              </div>
            )}

            {step === 1 && (
              <div style={{ display: "grid", gap: 20 }}>
                <div>
                  <label>Destination country</label>
                  <input type="text" placeholder="e.g. United Arab Emirates" value={data.country} onChange={e => set("country", e.target.value)} />
                </div>
                <div>
                  <label>Notes (optional)</label>
                  <textarea rows="4" placeholder="Lead time, packaging preferences, certifications required…"
                    value={data.notes} onChange={e => set("notes", e.target.value)} />
                </div>
              </div>
            )}

            {step === 2 && (
              <div className="form-2col">
                <div><label>Full name</label><input type="text" value={data.name} onChange={e => set("name", e.target.value)} /></div>
                <div><label>Company</label><input type="text" value={data.company} onChange={e => set("company", e.target.value)} /></div>
                <div><label>Email</label><input type="email" value={data.email} onChange={e => set("email", e.target.value)} /></div>
                <div><label>Phone (with country code)</label><input type="tel" value={data.phone} onChange={e => set("phone", e.target.value)} /></div>
              </div>
            )}

            <div style={{ display: "flex", justifyContent: "space-between", marginTop: 36 }}>
              <button className="btn btn-ghost" onClick={step === 0 ? onClose : back}>
                {step === 0 ? "Cancel" : "← Back"}
              </button>
              {step < 2 ? (
                <button className="btn btn-primary" disabled={!canNext} onClick={next}
                  style={{ opacity: canNext ? 1 : 0.4 }}>
                  Continue →
                </button>
              ) : (
                <button className="btn btn-primary" disabled={!canNext} onClick={() => setSubmitted(true)}
                  style={{ opacity: canNext ? 1 : 0.4 }}>
                  Submit quote request →
                </button>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, {
  Wordmark, Header, Footer, LeafSVG, FloatingLeaves, Reveal, SectionHeader, ImageFrame, Placeholder, QuoteModal
});
