/* Royal Yachts — main app */

const { useState: useS, useEffect: useE, useRef: useR } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": "editorial",
  "density": "comfortable",
  "displayItalic": true,
  "showFavBar": true,
  "displayFont": "cormorant"
}/*EDITMODE-END*/;

const PALETTES = {
  editorial: { /* warm paper editorial — DEFAULT */
    "--paper": "#F8F6F1",
    "--mist":  "#ECE7DD",
    "--ink":   "#10202E",
    "--marine":"#123A5A",
    "--noir":  "#07121C",
    "--foam":  "#FAFAF7",
    "--brass": "#B89263",
    "--brass-deep": "#8E6B3F"
  },
  marine: { /* cool marine — paper white + deep navy */
    "--paper": "#F2F4F6",
    "--mist":  "#E3E9EE",
    "--ink":   "#0E2032",
    "--marine":"#143C5C",
    "--noir":  "#05111C",
    "--foam":  "#F8FAFB",
    "--brass": "#9CB1C4",
    "--brass-deep": "#5A748A"
  },
  midnight: { /* full dark editorial */
    "--paper": "#0A1620",
    "--mist":  "#0F1F2C",
    "--ink":   "#E8EEF2",
    "--marine":"#7BA3C9",
    "--noir":  "#040A12",
    "--foam":  "#0D1A24",
    "--brass": "#D3AC74",
    "--brass-deep": "#B89263"
  }
};

const DISPLAY_FONTS = {
  cormorant: '"Cormorant Garamond", "EB Garamond", Georgia, serif',
  playfair:  '"Playfair Display", "EB Garamond", Georgia, serif',
  ebgaramond:'"EB Garamond", Georgia, serif'
};

function applyTweaks(t) {
  const r = document.documentElement;
  const p = PALETTES[t.palette] || PALETTES.editorial;
  Object.entries(p).forEach(([k, v]) => r.style.setProperty(k, v));
  // Recompute line/muted from ink so they stay readable
  if (t.palette === "midnight") {
    r.style.setProperty("--line", "rgba(232,238,242,0.14)");
    r.style.setProperty("--line-strong", "rgba(232,238,242,0.34)");
    r.style.setProperty("--muted", "rgba(232,238,242,0.62)");
  } else {
    r.style.setProperty("--line", "rgba(16,32,46,0.14)");
    r.style.setProperty("--line-strong", "rgba(16,32,46,0.32)");
    r.style.setProperty("--muted", "rgba(16,32,46,0.62)");
  }
  r.style.setProperty("--font-display", DISPLAY_FONTS[t.displayFont] || DISPLAY_FONTS.cormorant);
  r.style.setProperty("--section-pad", t.density === "tight" ? "72px" : t.density === "lavish" ? "128px" : "96px");
}

/* ---------- Toast ---------- */
function Toast({ msg, show }) {
  return (
    <div className={"toast " + (show ? "show" : "")}>
      <Icon.check />
      <span>{msg}</span>
    </div>
  );
}

/* ---------- Main App ---------- */
function App() {
  const [tweaks, setTweaks] = useTweaks(TWEAK_DEFAULTS);
  const [lang, setLang] = useS("en");
  const [favs, setFavs] = useS(() => {
    try { return JSON.parse(localStorage.getItem("ry_favs") || "[]"); } catch { return []; }
  });
  const [enquire, setEnquire] = useS({ open: false, payload: null });
  const [drawer, setDrawer] = useS({ open: false, yacht: null });
  const [toast, setToast] = useS({ show: false, msg: "" });

  const t = I18N[lang];

  useE(() => { applyTweaks(tweaks); }, [tweaks]);
  useE(() => {
    document.body.setAttribute("dir", t.dir);
  }, [lang]);
  useE(() => { localStorage.setItem("ry_favs", JSON.stringify(favs)); }, [favs]);

  const toggleFav = (id) => {
    setFavs((f) => {
      const has = f.includes(id);
      if (has) {
        setToast({ show: true, msg: "Removed from shortlist" });
      } else {
        setToast({ show: true, msg: "Added to shortlist · check the bottom-left" });
      }
      setTimeout(() => setToast((tt) => ({ ...tt, show: false })), 2400);
      return has ? f.filter((x) => x !== id) : [...f, id];
    });
  };

  const openEnquire = (payload = {}) => setEnquire({ open: true, payload });
  const closeEnquire = () => setEnquire({ open: false, payload: null });

  const openYacht = (yacht) => { setDrawer({ open: true, yacht }); document.body.style.overflow = "hidden"; };
  const closeYacht = () => { setDrawer({ open: false, yacht: drawer.yacht }); document.body.style.overflow = ""; };

  return (
    <React.Fragment>
      <Nav lang={lang} setLang={setLang} onEnquire={openEnquire} t={t} />
      <Hero t={t} onEnquire={openEnquire} />
      <TrustStrip t={t} />

      <section className="section tight">
        <DualEntry
          onCharter={() => document.getElementById("fleet").scrollIntoView({behavior:"smooth"})}
          onSales={() => document.getElementById("sales").scrollIntoView({behavior:"smooth"})}
          t={t}
        />
      </section>

      <section className="section" id="fleet">
        <div className="shell">
          <div className="section-head">
            <div>
              <span className="eyebrow"><span className="dot"/>{t.fleetEyebrow}</span>
              <h2 className="display">{t.fleetTitle} <span className="italic">{t.fleetTitleItalic}</span></h2>
            </div>
            <p>{t.fleetSub}</p>
          </div>

          <div className="fleet-grid">
            {FLEET.map((y, i) => (
              <YachtCard
                key={y.id}
                y={y}
                idx={i}
                faved={favs.includes(y.id)}
                onFave={toggleFav}
                onOpen={openYacht}
                onEnquire={openEnquire}
              />
            ))}
          </div>

          <div style={{display:"flex", justifyContent:"center", marginTop:64, gap:12, alignItems:"center"}}>
            <span style={{height:1, background:"var(--line)", width:120}} />
            <span className="mono" style={{color:"var(--muted)"}}>FLEET ROTATES SEASONALLY · 43 — 280 FT</span>
            <span style={{height:1, background:"var(--line)", width:120}} />
          </div>
        </div>
      </section>

      <section className="section dark" id="experiences">
        <div className="shell">
          <div className="section-head">
            <div>
              <span className="eyebrow on-dark"><span className="dot"/>{t.expEyebrow}</span>
              <h2 className="display" style={{color:"var(--paper)"}}>{t.expTitle} <span className="italic">{t.expTitleItalic}</span></h2>
            </div>
            <p style={{color:"rgba(255,255,255,0.7)"}}>{t.expSub}</p>
          </div>

          <ExperienceGrid exps={EXPERIENCES} onEnquire={openEnquire} />
        </div>
      </section>

      <section className="section" id="destinations">
        <div className="shell">
          <div className="section-head">
            <div>
              <span className="eyebrow"><span className="dot"/>{t.destEyebrow}</span>
              <h2 className="display">{t.destTitle} <span className="italic">{t.destTitleItalic}</span></h2>
            </div>
            <p>{t.destSub}</p>
          </div>
          <DestinationRail dests={DESTINATIONS} onEnquire={openEnquire} />
        </div>
      </section>

      <SalesBand onEnquire={openEnquire} />

      <Legacy onEnquire={openEnquire} t={t} />

      <Footer onEnquire={openEnquire} />

      {/* Floating UI */}
      <YachtDrawer
        yacht={drawer.yacht}
        open={drawer.open}
        onClose={closeYacht}
        onEnquire={(p) => { closeYacht(); openEnquire(p); }}
        faved={drawer.yacht ? favs.includes(drawer.yacht.id) : false}
        onFave={toggleFav}
      />

      <EnquireModal
        open={enquire.open}
        payload={enquire.payload}
        onClose={closeEnquire}
        onSubmit={() => {}}
      />

      {/* Sticky CTAs */}
      <div className="fab">
        <a
          className="fab-btn wa"
          href="https://wa.me/971502266906?text=Hi%20Royal%20Yachts%2C%20I'd%20like%20to%20enquire."
          target="_blank" rel="noreferrer"
          aria-label="Chat on WhatsApp"
        >
          <Icon.wa /> WhatsApp the charter desk
        </a>
      </div>

      {tweaks.showFavBar && favs.length > 0 && (
        <div className={"fav-bar show"}>
          <div>
            <div className="count ed-display">{String(favs.length).padStart(2,"0")}</div>
          </div>
          <div>
            <div className="lbl">Yachts</div>
            <div className="lbl" style={{color:"var(--paper)"}}>{t.favBarCount}</div>
          </div>
          <button onClick={() => openEnquire({ intent: "charter", favs })}>{t.favBarCta} →</button>
        </div>
      )}

      <Toast msg={toast.msg} show={toast.show} />

      {/* Tweaks panel */}
      <RyTweaks tweaks={tweaks} setTweak={setTweaks} />
    </React.Fragment>
  );
}

/* ---------- Tweaks panel ---------- */
function RyTweaks({ tweaks, setTweak }) {
  return (
    <TweaksPanel title="Royal Yachts · Tweaks">
      <TweakSection title="Palette">
        <TweakRadio
          label=""
          value={tweaks.palette}
          options={[
            { value: "editorial", label: "Editorial" },
            { value: "marine", label: "Marine" },
            { value: "midnight", label: "Midnight" },
          ]}
          onChange={(v) => setTweak("palette", v)}
        />
      </TweakSection>
      <TweakSection title="Display type">
        <TweakSelect
          label="Family"
          value={tweaks.displayFont}
          options={[
            { value: "cormorant", label: "Cormorant Garamond" },
            { value: "playfair",  label: "Playfair Display" },
            { value: "ebgaramond",label: "EB Garamond" },
          ]}
          onChange={(v) => setTweak("displayFont", v)}
        />
        <TweakToggle
          label="Italic accents on titles"
          value={tweaks.displayItalic}
          onChange={(v) => {
            setTweak("displayItalic", v);
            document.documentElement.style.setProperty("--italic-display", v ? "italic" : "normal");
            document.querySelectorAll(".display .italic").forEach((el) => {
              el.style.fontStyle = v ? "italic" : "normal";
            });
          }}
        />
      </TweakSection>
      <TweakSection title="Layout">
        <TweakRadio
          label="Section rhythm"
          value={tweaks.density}
          options={[
            { value: "tight", label: "Tight" },
            { value: "comfortable", label: "Comfortable" },
            { value: "lavish", label: "Lavish" },
          ]}
          onChange={(v) => setTweak("density", v)}
        />
        <TweakToggle
          label="Show shortlist bar"
          value={tweaks.showFavBar}
          onChange={(v) => setTweak("showFavBar", v)}
        />
      </TweakSection>
    </TweaksPanel>
  );
}

Object.assign(window, { App, RyTweaks });

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