/* Down The Cove homepage — reviews, guides, newsletter, footer, overlays */
const { Button, Input } = window.DownTheCoveDesignSystem_3cc6fe;
const MIcon = window.DtcIcon;

function Stars({ value, size = 13 }) {
  return (
    <span className="hp-review__stars" aria-label={value + " out of 5"}>
      {[0, 1, 2, 3, 4].map((i) => (
        <svg key={i} width={size} height={size} viewBox="0 0 24 24"
             fill={i < Math.round(value) ? "var(--coral)" : "#e6e2d6"}>
          <path d="M11.5 2.3l2.7 5.5 6 .9-4.3 4.2 1 6-5.4-2.8-5.4 2.8 1-6L3.5 8.7l6-.9z" />
        </svg>
      ))}
    </span>
  );
}

function Reviews({ reviews }) {
  return (
    <section className="hp-section">
      <div className="hp-section__head">
        <div>
          <p className="hp-eyebrow">Loved along the coast & beyond</p>
          <h2 className="hp-title">Real shoppers, real advice</h2>
        </div>
      </div>
      <div className="hp-reviews__agg">
        <span className="hp-reviews__score">4.8</span>
        <div className="hp-reviews__meta">
          <Stars value={5} size={15} />
          <div>Rated <strong>excellent</strong> · 2,400+ reviews</div>
        </div>
      </div>
      <div className="hp-revrail">
        {reviews.map((r, i) => (
          <article className="hp-review" key={i}>
            <Stars value={r.rating} />
            <p className="hp-review__text">“{r.text}”</p>
            <div className="hp-review__who">
              <span className="hp-review__av">{r.name.charAt(0)}</span>
              <div>
                <div className="hp-review__name">{r.name}</div>
                <div className="hp-review__place">{r.place}</div>
              </div>
              <span className="hp-review__verified"><MIcon name="check" size={12} /> Verified</span>
            </div>
          </article>
        ))}
      </div>
    </section>
  );
}

function Guides({ guides, onAll }) {
  return (
    <section className="hp-section">
      <div className="hp-section__head">
        <div>
          <p className="hp-eyebrow">Knowledge guides</p>
          <h2 className="hp-title">Helpful before you buy</h2>
        </div>
        <a className="hp-seeall" href="#" onClick={(e) => { e.preventDefault(); onAll(); }}>
          159+ guides <MIcon name="chevron-right" size={15} />
        </a>
      </div>
      <div className="hp-guides">
        {guides.map((g, i) => (
          <a className="hp-guide" href="#" key={i} onClick={(e) => e.preventDefault()}>
            <img className="hp-guide__img" src={"assets/" + g.img} alt="" />
            <div className="hp-guide__body">
              <span className="hp-guide__tag">{g.tag}</span>
              <h3 className="hp-guide__title">{g.title}</h3>
              <span className="hp-guide__read">{g.read}</span>
            </div>
            <MIcon name="chevron-right" size={18} className="hp-guide__arrow" />
          </a>
        ))}
      </div>
    </section>
  );
}

function Newsletter() {
  const [email, setEmail] = React.useState("");
  const [done, setDone] = React.useState(false);
  const [err, setErr] = React.useState("");
  const submit = (e) => {
    e.preventDefault();
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) { setErr("Pop in a valid email address."); return; }
    setErr(""); setDone(true);
  };
  return (
    <section className="hp-section">
      <div className="hp-news">
        <h2 className="hp-news__title">10% off your first order over £30</h2>
        <p className="hp-news__body">
          Join the list for coastal tips, new arrivals and the odd members' offer. No spam — just useful things.
        </p>
        {done ? (
          <div className="hp-news__ok"><MIcon name="check" size={18} /> You're in — check your inbox for the code.</div>
        ) : (
          <form className="hp-news__form" onSubmit={submit} noValidate>
            <div className="hp-news__row">
              <div className="dtc-input-wrap">
                <span className="dtc-input-wrap__icon"><MIcon name="mail" size={16} /></span>
                <input className="dtc-input" type="email" placeholder="you@example.com" value={email}
                       aria-label="Email address" aria-invalid={!!err}
                       onChange={(e) => { setEmail(e.target.value); if (err) setErr(""); }} />
              </div>
              <Button variant="primary" size="lg" type="submit">Sign up</Button>
            </div>
            {err ? <p className="hp-news__err">{err}</p> : null}
          </form>
        )}
        <p className="hp-news__fine">By signing up you agree to our privacy policy. Unsubscribe anytime.</p>
      </div>
    </section>
  );
}

function FooterCol({ col }) {
  const [open, setOpen] = React.useState(false);
  return (
    <div className="hp-acc">
      <button className="hp-acc__btn" data-open={open} onClick={() => setOpen((o) => !o)} aria-expanded={open}>
        {col.h}<MIcon name="chevron-down" size={18} />
      </button>
      <div className="hp-acc__panel" data-open={open}>
        <ul className="hp-acc__links">
          {col.links.map((l) => <li key={l}><a href="#" onClick={(e) => e.preventDefault()}>{l}</a></li>)}
        </ul>
      </div>
    </div>
  );
}

function Footer() {
  const cols = [
    { h: "Shop the cove", links: ["Fishing gear", "Cook shop", "Food smoking", "Home decor", "Coastal gifts"] },
    { h: "Learn & explore", links: ["Knowledge guides", "Recipes", "Species finder", "Coastlines"] },
    { h: "Help & orders", links: ["Delivery & returns", "Track an order", "Contact us", "FAQs"] },
    { h: "Join us", links: ["Cove Club", "Wholesale", "Affiliates", "Gift cards"] },
  ];
  const trust = [
    { i: "truck", t: "Free delivery over £30" },
    { i: "map-pin", t: "Founded in Cornwall" },
    { i: "heart", t: "Family-owned & helpful" },
    { i: "shield-check", t: "Secure checkout" },
  ];
  return (
    <footer className="hp-footer">
      <div className="hp-footer__brand">
        <img className="hp-footer__logo" src="assets/logo/logo.png" alt="Down The Cove" />
        <div className="hp-footer__script">packed with a bit of pride</div>
        <p className="hp-footer__tag">Useful coastal things, chosen with care — shipped right across the UK from Cornwall.</p>
      </div>
      {cols.map((c) => <FooterCol key={c.h} col={c} />)}
      <div className="hp-footer__trust">
        {trust.map((t) => (
          <div className="hp-footer__trustitem" key={t.t}><MIcon name={t.i} size={16} />{t.t}</div>
        ))}
      </div>
      <div className="hp-footer__pay">
        {["VISA", "MASTERCARD", "AMEX", "PAYPAL", "APPLE PAY", "G PAY"].map((p) => (
          <span className="hp-paychip" key={p}>{p}</span>
        ))}
      </div>
      <div className="hp-footer__legal">
        <p>© {new Date().getFullYear()} Down The Cove. Coastal essentials, useful knowledge and thoughtful gifts for life by the water.</p>
        <p>Down The Cove Group LTD · Registered in England &amp; Wales no. 16784991 · VAT GB504551223</p>
      </div>
      <img className="hp-footer__strip" src="assets/brand/beach-strip.png" alt="" />
    </footer>
  );
}

/* ── Search overlay ───────────────────────────────────────── */
function SearchOverlay({ open, query, onQuery, onClose, results, onPick }) {
  const inputRef = React.useRef(null);
  React.useEffect(() => { if (open && inputRef.current) setTimeout(() => inputRef.current.focus(), 80); }, [open]);
  const suggestions = ["Father's Day gifts", "Smoking kit", "Crabbing set", "Seafood tools", "Under £30"];
  return (
    <div className="hp-overlay" data-open={open} aria-hidden={!open} style={{ pointerEvents: open ? "auto" : "none" }}>
      <div className="hp-overlay__scrim" onClick={onClose} />
      <div className="hp-search">
        <div className="hp-search__head">
          <div className="hp-search__field">
            <div className="dtc-input-wrap">
              <span className="dtc-input-wrap__icon"><MIcon name="search" size={16} /></span>
              <input ref={inputRef} className="dtc-input" placeholder="Search the cove…" value={query}
                     aria-label="Search products" onChange={(e) => onQuery(e.target.value)} />
            </div>
          </div>
          <button className="hp-search__cancel" onClick={onClose}>Cancel</button>
        </div>
        <div className="hp-search__body">
          {!query.trim() ? (
            <React.Fragment>
              <p className="hp-search__lbl">Popular searches</p>
              <div className="hp-search__sugg">
                {suggestions.map((s) => (
                  <button className="hp-chip" key={s} onClick={() => onQuery(s === "Under £30" || s === "Father's Day gifts" ? "" : s.split(" ")[0])}>{s}</button>
                ))}
              </div>
              <p className="hp-search__lbl">Trending products</p>
              <div className="hp-search__res">
                {results.slice(0, 4).map((p) => (
                  <a className="hp-search__resrow" href="#" key={p.id} onClick={(e) => { e.preventDefault(); onPick(p); }}>
                    <img src={window.DTC.pimg(p)} alt="" />
                    <div>
                      <div className="hp-search__resname">{p.name}</div>
                      <div className="hp-search__rescat">{p.cat}</div>
                    </div>
                    <span className="hp-search__resprice">{p.price}</span>
                  </a>
                ))}
              </div>
            </React.Fragment>
          ) : (
            <React.Fragment>
              <p className="hp-search__lbl">{results.length} result{results.length === 1 ? "" : "s"}</p>
              <div className="hp-search__res">
                {results.length === 0 ? (
                  <p style={{ color: "var(--text-muted)", fontSize: "0.9rem" }}>Nothing matched — try “smoking”, “gift” or “crab”.</p>
                ) : results.map((p) => (
                  <a className="hp-search__resrow" href="#" key={p.id} onClick={(e) => { e.preventDefault(); onPick(p); }}>
                    <img src={window.DTC.pimg(p)} alt="" />
                    <div>
                      <div className="hp-search__resname">{p.name}</div>
                      <div className="hp-search__rescat">{p.cat}</div>
                    </div>
                    <span className="hp-search__resprice">{p.price}</span>
                  </a>
                ))}
              </div>
            </React.Fragment>
          )}
        </div>
      </div>
    </div>
  );
}

/* ── Cart bottom sheet ────────────────────────────────────── */
function CartSheet({ open, items, products, onClose, onQty }) {
  const byId = Object.fromEntries(products.map((p) => [p.id, p]));
  const lines = Object.entries(items).filter(([, q]) => q > 0);
  const total = lines.reduce((s, [id, q]) => s + q * parseFloat(byId[id].price.replace("£", "")), 0);
  const met = total >= 30;
  const pct = Math.min(100, (total / 30) * 100);
  return (
    <div className="hp-overlay" data-open={open} aria-hidden={!open} style={{ pointerEvents: open ? "auto" : "none" }}>
      <div className="hp-overlay__scrim" onClick={onClose} />
      <div className="hp-sheet" role="dialog" aria-label="Your basket">
        <div className="hp-sheet__grip" />
        <div className="hp-sheet__head">
          <h3>Your basket{lines.length ? ` · ${lines.reduce((a, [, q]) => a + q, 0)}` : ""}</h3>
          <button className="hp-iconbtn" onClick={onClose} aria-label="Close basket"><MIcon name="x" size={20} /></button>
        </div>
        {lines.length === 0 ? (
          <div className="hp-sheet__empty">
            <MIcon name="shopping-bag" size={34} />
            <p>Your basket's empty.<br />Let's find something useful.</p>
            <Button variant="primary" onClick={onClose}>Keep shopping</Button>
          </div>
        ) : (
          <React.Fragment>
            <div className="hp-sheet__ship" data-met={met}>
              <MIcon name="truck" size={16} />
              {met ? "You've unlocked free UK delivery." : `Add £${(30 - total).toFixed(2)} more for free delivery.`}
            </div>
            <div style={{ margin: "0.4rem 1.2rem 0" }}>
              <div className="hp-sheet__bar"><i style={{ width: pct + "%" }} /></div>
            </div>
            <div className="hp-sheet__lines">
              {lines.map(([id, q]) => {
                const p = byId[id];
                return (
                  <div className="hp-line" key={id}>
                    <img className="hp-line__img" src={window.DTC.pimg(p)} alt="" />
                    <div className="hp-line__info">
                      <p className="hp-line__name">{p.name}</p>
                      <p className="hp-line__cat">{p.cat}</p>
                      <div className="hp-step">
                        <button onClick={() => onQty(id, q - 1)} aria-label="Decrease"><MIcon name="minus" size={13} /></button>
                        <span>{q}</span>
                        <button onClick={() => onQty(id, q + 1)} aria-label="Increase"><MIcon name="plus" size={13} /></button>
                      </div>
                    </div>
                    <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: "0.4rem" }}>
                      <span className="hp-line__price">{p.price}</span>
                      <button className="hp-line__remove" onClick={() => onQty(id, 0)}>Remove</button>
                    </div>
                  </div>
                );
              })}
            </div>
            <div className="hp-sheet__foot">
              <div className="hp-sheet__total"><span>Subtotal</span><strong>£{total.toFixed(2)}</strong></div>
              <p className="hp-sheet__sub">Taxes included. Delivery calculated at checkout.</p>
              <Button variant="primary" block size="lg" rightIcon={<MIcon name="arrow-right" size={16} />}>Secure checkout</Button>
            </div>
          </React.Fragment>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { Reviews, Guides, Newsletter, Footer, SearchOverlay, CartSheet });
