/* Royal Yachts — yacht drawer + enquire modal + sales/legacy/footer */

const { useState: useStateD, useEffect: useEffectD, useMemo } = React;

/* ---------- Yacht drawer ---------- */
function YachtDrawer({ yacht, open, onClose, onEnquire, faved, onFave }) {
  useEffectD(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    if (open) window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  if (!yacht) return null;

  return (
    <React.Fragment>
      <div className={"drawer-scrim " + (open ? "open" : "")} onClick={onClose} />
      <aside className={"drawer " + (open ? "open" : "")} aria-hidden={!open}>
        <div className="drawer-head">
          <div style={{display:"flex", alignItems:"baseline", gap:14}}>
            <span className="mono" style={{color:"var(--muted)"}}>CHARTER YACHT</span>
            <span className="mono" style={{color:"var(--brass-deep)"}}>· DUBAI MARINA</span>
          </div>
          <div style={{display:"flex", gap:10}}>
            <button
              className={"yacht-fave " + (faved ? "on" : "")}
              style={{position:"static", width:40, height:40}}
              onClick={() => onFave(yacht.id)}
              aria-label="Shortlist"
            >
              {Icon.heart(faved)}
            </button>
            <button className="drawer-close" onClick={onClose} aria-label="Close"><Icon.close /></button>
          </div>
        </div>

        <div className="drawer-hero" style={{ backgroundImage: `url('${yacht.hero}')` }}>
          <div className="drawer-hero-body">
            <div>
              <span className="eyebrow on-dark"><span className="dot"/>{yacht.builder} · {yacht.year}</span>
              <h2 className="display" style={{marginTop:8}}>{yacht.name}</h2>
            </div>
            <span className="mono" style={{color:"rgba(255,255,255,0.8)"}}>{yacht.home}</span>
          </div>
        </div>

        <div className="drawer-spec-strip">
          <div className="item"><div className="l">Length</div><div className="v ed-display">{yacht.length}<span style={{fontSize:14, color:"var(--muted)", marginInlineStart:4, fontFamily:"var(--font-mono)", letterSpacing:".06em"}}>FT</span></div></div>
          <div className="item"><div className="l">Guests</div><div className="v ed-display">{yacht.guests}</div></div>
          <div className="item"><div className="l">Cabins</div><div className="v ed-display">{yacht.cabins}</div></div>
          <div className="item"><div className="l">Crew</div><div className="v ed-display">{yacht.crew}</div></div>
          <div className="item"><div className="l">Builder</div><div className="v ed-display" style={{fontSize:18, lineHeight:1.2}}>{yacht.builder}</div></div>
          <div className="item"><div className="l">Year</div><div className="v ed-display">{yacht.year}</div></div>
        </div>

        <div className="drawer-body">
          <span className="indicative">Indicative spec · client to confirm</span>
          <h3 className="display" style={{marginTop:18}}>{yacht.summary.split(" — ")[0]} <span style={{color:"var(--muted)"}}>—</span></h3>
          <p>{yacht.summary}</p>

          <div className="drawer-grid">
            <div>
              <span className="eyebrow">Gallery</span>
              <div className="drawer-gallery" style={{marginTop:14}}>
                {yacht.gallery.map((src, i) => (
                  <img key={i} src={src} alt={`${yacht.name} ${i + 1}`} loading="lazy" />
                ))}
              </div>

              <span className="eyebrow" style={{display:"block", marginTop:40, marginBottom:14}}>Best fit</span>
              <div style={{display:"flex", gap:10, flexWrap:"wrap"}}>
                {yacht.fit.map((f) => (
                  <span key={f} style={{
                    border:"1px solid var(--line-strong)",
                    padding:"8px 14px",
                    fontSize:13,
                    fontFamily:"var(--font-display)",
                    fontStyle:"italic"
                  }}>{f}</span>
                ))}
              </div>
            </div>

            <div>
              <span className="eyebrow">Onboard</span>
              <div className="drawer-inclusions" style={{marginTop:14}}>
                {yacht.inclusions.map((inc, i) => (
                  <div key={i} className="row">
                    <Icon.check />
                    <span>{inc}</span>
                  </div>
                ))}
              </div>

              <span className="eyebrow" style={{display:"block", marginTop:32, marginBottom:14}}>Route ideas</span>
              <ul style={{listStyle:"none", padding:0, margin:0, fontSize:14}}>
                <li style={{padding:"10px 0", borderBottom:"1px dashed var(--line)"}}>Marina → Palm fountains → Burj Al Arab</li>
                <li style={{padding:"10px 0", borderBottom:"1px dashed var(--line)"}}>Marina → World Islands → sunset return</li>
                <li style={{padding:"10px 0"}}>Marina → Dubai Water Canal night-cruise</li>
              </ul>
            </div>
          </div>
        </div>

        <div className="drawer-cta-bar">
          <div className="price-q">
            Charter rate · <b>On request</b>
          </div>
          <div style={{display:"flex", gap:10}}>
            <a className="btn" href={`https://wa.me/971502266906?text=${encodeURIComponent("Hi Royal Yachts, I'd like to enquire about " + yacht.name + ".")}`} target="_blank" rel="noreferrer">
              <Icon.wa /> WhatsApp
            </a>
            <button className="btn" onClick={() => onEnquire({ yachtId: yacht.id, intent: "charter" })}>
              Check availability <Icon.arrow />
            </button>
            <button className="btn primary" onClick={() => onEnquire({ yachtId: yacht.id, intent: "charter" })}>
              Request a quote <Icon.arrow />
            </button>
          </div>
        </div>
      </aside>
    </React.Fragment>
  );
}

/* ---------- Enquire modal ---------- */
function EnquireModal({ open, payload, onClose, onSubmit }) {
  const [form, setForm] = useStateD({
    name: "", phone: "", date: "", guests: "", message: "",
  });
  const [stage, setStage] = useStateD("form"); // form | success
  const yacht = payload?.yachtId ? FLEET.find((y) => y.id === payload.yachtId) : null;
  const intent = payload?.intent || "general";

  useEffectD(() => {
    if (open) {
      setStage("form");
      setForm({ name: "", phone: "", date: "", guests: "", message: yacht ? `I'd like to charter the ${yacht.name}.` : "" });
    }
  }, [open, payload]);

  useEffectD(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    if (open) window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  const submit = (e) => {
    e.preventDefault();
    setStage("success");
    onSubmit && onSubmit(form, payload);
  };

  const waLink = useMemo(() => {
    const text =
      "Hi Royal Yachts — I'd like to enquire" +
      (yacht ? ` about the ${yacht.name}` : "") +
      (form.date ? `, on ${form.date}` : "") +
      (form.guests ? `, ${form.guests} guests` : "") +
      ".";
    return `https://wa.me/971502266906?text=${encodeURIComponent(text)}`;
  }, [form, yacht]);

  const titleByIntent = {
    charter: "Reserve your day on the water",
    experience: "Plan your experience",
    destination: "Build the route",
    sales: "Speak with the sales desk",
    general: "Tell us what you'd like",
  };

  return (
    <div className={"modal-scrim " + (open ? "open" : "")} onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal-head">
          <div>
            <span className="eyebrow"><span className="dot"/>{intent === "sales" ? "Sales · Ownership" : "Charter Enquiry"}</span>
            <h3 className="display" style={{marginTop:6}}>
              {stage === "form" ? titleByIntent[intent] : "We have you."}
            </h3>
            {stage === "form" && (
              <p>{yacht ? `Quoting the ${yacht.name}. We'll route the date and crew within 24 hours.` : "We answer every enquiry within 24 hours. Office hours 09:00–17:00 GST."}</p>
            )}
            {stage === "success" && (
              <p>One of the team will reply within 24 hours. For an instant route, open WhatsApp below.</p>
            )}
          </div>
          <button className="drawer-close" onClick={onClose} style={{flexShrink:0}}><Icon.close /></button>
        </div>

        {stage === "form" && (
          <form onSubmit={submit}>
            <div className="modal-body">
              <div className="field">
                <label>Name</label>
                <input required value={form.name} onChange={(e) => setForm({...form, name: e.target.value})} placeholder="Your name" />
              </div>
              <div className="field">
                <label>Phone / WhatsApp</label>
                <input required value={form.phone} onChange={(e) => setForm({...form, phone: e.target.value})} placeholder="+971 ..." />
              </div>
              <div className="field">
                <label>Date</label>
                <input type="date" value={form.date} onChange={(e) => setForm({...form, date: e.target.value})} />
              </div>
              <div className="field">
                <label>Guests</label>
                <select value={form.guests} onChange={(e) => setForm({...form, guests: e.target.value})}>
                  <option value="">Select</option>
                  <option>1 – 6</option>
                  <option>7 – 12</option>
                  <option>13 – 25</option>
                  <option>26 – 50</option>
                  <option>50 +</option>
                </select>
              </div>
              <div className="field full">
                <label>Brief</label>
                <textarea value={form.message} onChange={(e) => setForm({...form, message: e.target.value})} placeholder="Occasion, route ideas, anything we should know..." />
              </div>
            </div>
            <div className="modal-foot">
              <span className="or">Or skip the form — message us directly</span>
              <div style={{display:"flex", gap:10}}>
                <a className="btn" href={waLink} target="_blank" rel="noreferrer"><Icon.wa /> WhatsApp</a>
                <button className="btn primary" type="submit">Send enquiry <Icon.arrow /></button>
              </div>
            </div>
          </form>
        )}

        {stage === "success" && (
          <div style={{padding:"32px 36px 36px"}}>
            <div style={{
              border:"1px solid var(--line)",
              padding:"22px 24px",
              marginBottom:24,
              display:"flex", alignItems:"flex-start", gap:16
            }}>
              <Icon.check style={{color:"var(--brass-deep)", marginTop:4, flexShrink:0}}/>
              <div>
                <strong style={{display:"block", marginBottom:4}}>Enquiry routed to the charter desk.</strong>
                <span style={{color:"var(--muted)", fontSize:13.5}}>
                  Ref&nbsp;<span className="mono" style={{color:"var(--ink)"}}>RY-{Math.floor(Math.random() * 9000 + 1000)}</span>
                  &nbsp;· {yacht ? yacht.name + " · " : ""}{form.date || "date TBC"}{form.guests ? " · " + form.guests + " guests" : ""}
                </span>
              </div>
            </div>
            <div style={{display:"flex", gap:10, justifyContent:"flex-end"}}>
              <a className="btn" href={waLink} target="_blank" rel="noreferrer"><Icon.wa /> Open WhatsApp now</a>
              <button className="btn primary" onClick={onClose}>Continue browsing</button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

/* ---------- Sales band ---------- */
function SalesBand({ onEnquire }) {
  return (
    <section className="sales" id="sales">
      <div className="sales-vis" style={{ backgroundImage: "url('media/yacht-galeon-780-exterior.webp')" }} />
      <div className="sales-body">
        <span className="eyebrow on-dark"><span className="dot"/>Half the firm</span>
        <h2 className="display">Beyond the charter — <span className="italic">the lifecycle.</span></h2>
        <p style={{color:"rgba(255,255,255,0.78)", fontSize:15.5, maxWidth:520}}>
          Half of Royal Yachts is a brokerage. We sell, build, manage, and co-own — whichever stage of the asset you're at, the same people who know the boat from the inside know the paperwork from the outside.
        </p>
        <div className="pillars">
          <div className="pillar"><h4 className="display">Brokerage</h4><p>Pre-owned & new yachts, Dubai and a curated Europe selection. No invented listings — by enquiry.</p></div>
          <div className="pillar"><h4 className="display">Build-a-yacht</h4><p>New-build commissioning with shipyards in Europe and the Gulf — to your specification.</p></div>
          <div className="pillar"><h4 className="display">Co-ownership</h4><p>Fractional programmes for owners who use the boat enough to want it, not enough to need all of it.</p></div>
          <div className="pillar"><h4 className="display">Management</h4><p>Operations, maintenance, crewing and charter-management for owners who'd rather not.</p></div>
        </div>
        <div style={{display:"flex", gap:12, marginTop:14}}>
          <button className="btn on-dark" onClick={() => onEnquire({ intent: "sales" })}>Book a consultation <Icon.arrow /></button>
          <a className="btn on-dark" href="tel:+971508844109"><Icon.call /> +971 50 884 4109 · Sales</a>
        </div>
      </div>
    </section>
  );
}

/* ---------- Legacy band ---------- */
function Legacy({ onEnquire, t }) {
  return (
    <section className="section sand" id="legacy">
      <div className="shell legacy">
        <div className="legacy-img" style={{ backgroundImage: "url('media/about-our-legacy.webp')" }} />
        <div className="legacy-body">
          <span className="eyebrow"><span className="dot"/>{t.legacyEyebrow}</span>
          <h2 className="display">{t.legacyTitle} <span className="italic">{t.legacyTitleItalic}</span></h2>
          <p>{t.legacyBody}</p>
          <div className="legacy-stats">
            <div><div className="v ed-display">2011</div><div className="l">Founded</div></div>
            <div><div className="v ed-display">2 <span style={{fontSize:18, color:"var(--muted)"}}>regions</span></div><div className="l">MENA · Europe</div></div>
            <div><div className="v ed-display">LMA</div><div className="l">Accredited member</div></div>
          </div>
          <div style={{marginTop:32, display:"flex", gap:12}}>
            <a className="btn" href="#contact">Our team <Icon.arrow /></a>
            <button className="btn ghost" onClick={() => onEnquire({ intent: "general" })}>Speak with us</button>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- Contact + Footer ---------- */
function Footer({ onEnquire }) {
  return (
    <footer className="footer" id="contact">
      <div className="shell">
        <div className="footer-top">
          <div>
            <img src="media/logo-royal-yachts-1.svg" style={{height:24, filter:"brightness(0) invert(1)"}} alt="Royal Yachts"/>
            <p className="brand-pitch">From first call to last mooring — <span style={{fontStyle:"italic"}}>handled.</span></p>
            <p style={{color:"rgba(255,255,255,0.6)", fontSize:13.5, marginTop:18, maxWidth:380}}>
              Royal Yachts LLC · Office #1004, Boulevard Plaza Tower 2, Downtown Dubai — boarding at Dubai Marina.
            </p>
          </div>

          <div>
            <h5>Charter</h5>
            <ul>
              <li><a href="#fleet">Fleet</a></li>
              <li><a href="#experiences">Experiences</a></li>
              <li><a href="#destinations">Destinations</a></li>
              <li><a href="#" onClick={(e) => {e.preventDefault(); onEnquire({intent:"experience", experienceId:"f1"})}}>F1 Abu Dhabi GP</a></li>
              <li><a href="#" onClick={(e) => {e.preventDefault(); onEnquire({intent:"experience", experienceId:"seabob"})}}>Seabob & watersports</a></li>
            </ul>
          </div>

          <div>
            <h5>Ownership</h5>
            <ul>
              <li><a href="#sales">Yachts for sale</a></li>
              <li><a href="#sales">Europe selection</a></li>
              <li><a href="#sales">Build a yacht</a></li>
              <li><a href="#sales">Co-ownership</a></li>
              <li><a href="#sales">List your vessel</a></li>
              <li><a href="#sales">Yacht management</a></li>
            </ul>
          </div>

          <div>
            <h5>Contact</h5>
            <ul>
              <li><a href="tel:+97145514040">Office · +971 4 551 4040</a></li>
              <li><a href="tel:+971502266906">Charter · +971 50 226 6906</a></li>
              <li><a href="tel:+971508844109">Sales · +971 50 884 4109</a></li>
              <li><a href="mailto:info@ry.ae">info@ry.ae</a></li>
              <li><a href="https://wa.me/971502266906" target="_blank" rel="noreferrer">WhatsApp the charter desk →</a></li>
            </ul>
          </div>
        </div>

        <div className="footer-bottom">
          <span>© 2011 — 2026 Royal Yachts LLC · A member of the Leisure Marine Association</span>
          <span>Dubai · London · Mediterranean</span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, {
  YachtDrawer, EnquireModal, SalesBand, Legacy, Footer
});
