/* QuoteDrawer, top-down slide-in panel below the TopNav.
   Listens for scdquote:open / scdquote:added / scdquote:close events.
   Slides down on first add, toasts on subsequent adds. */

function useQuoteItems() {
  const [items, setItems] = React.useState(() => window.__scdQuote ? window.__scdQuote.items() : []);
  React.useEffect(() => {
    if (!window.__scdQuote) return;
    return window.__scdQuote.subscribe(next => setItems(next.slice()));
  }, []);
  return items;
}

function QuoteDrawer() {
  const items = useQuoteItems();
  const [open, setOpen] = React.useState(false);
  const [toast, setToast] = React.useState(null);
  const seenFirstAdd = React.useRef(false);
  const toastTimer = React.useRef(0);

  React.useEffect(() => {
    function onOpen() { setOpen(true); }
    function onClose() { setOpen(false); }
    function onAdded(e) {
      const item = e.detail && e.detail.item;
      if (!seenFirstAdd.current) {
        seenFirstAdd.current = true;
        setOpen(true);
      } else {
        // Toast
        setToast(item);
        clearTimeout(toastTimer.current);
        toastTimer.current = setTimeout(() => setToast(null), 3200);
      }
    }
    window.addEventListener("scdquote:open", onOpen);
    window.addEventListener("scdquote:close", onClose);
    window.addEventListener("scdquote:added", onAdded);
    return () => {
      window.removeEventListener("scdquote:open", onOpen);
      window.removeEventListener("scdquote:close", onClose);
      window.removeEventListener("scdquote:added", onAdded);
      clearTimeout(toastTimer.current);
    };
  }, []);

  // Lock body scroll while drawer open
  React.useEffect(() => {
    if (open) document.body.style.overflow = "hidden";
    else document.body.style.overflow = "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  function handleContinue() {
    window.__scdQuote.setHandoff();
    window.location.href = "b2b-wholesale-v1.html#quote-form";
  }

  return (
    <React.Fragment>
      {/* Backdrop */}
      <div
        className="quote-backdrop"
        data-open={open ? "true" : "false"}
        onClick={() => setOpen(false)}
        aria-hidden="true"
      />

      {/* Drawer */}
      <aside
        className="quote-drawer"
        data-open={open ? "true" : "false"}
        role="dialog"
        aria-label="Quote request"
        aria-hidden={!open}
      >
        <header className="quote-drawer__head">
          <div>
            <div className="quote-drawer__eyebrow">B2B &middot; quote request</div>
            <h2 className="quote-drawer__title">
              Your quote list
              <span className="quote-drawer__count">
                {items.reduce((n, i) => n + i.qty, 0)} {items.reduce((n, i) => n + i.qty, 0) === 1 ? "item" : "items"}
              </span>
            </h2>
          </div>
          <button className="quote-drawer__close" onClick={() => setOpen(false)} aria-label="Close quote drawer">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
          </button>
        </header>

        <div className="quote-drawer__body">
          {items.length === 0 ? (
            <div className="quote-drawer__empty">
              <p>
                Your quote list is empty. Browse{" "}
                <a href="collection-rotary-trimmers-v1.html" className="text-link">rotary trimmers</a>{" "}
                and tap <em>Add to quote</em> on any item to start a list.
              </p>
            </div>
          ) : (
            <ul className="quote-drawer__list">
              {items.map(it => (
                <QuoteLine key={it.sku} item={it}/>
              ))}
            </ul>
          )}
        </div>

        <footer className="quote-drawer__foot">
          <p className="quote-drawer__note">
            Pricing and net-30 terms sent within 1 business day. No sales calls
            unless you ask.
          </p>
          <button
            type="button"
            className="btn btn--primary"
            disabled={items.length === 0}
            onClick={handleContinue}
            style={{ width: "100%", justifyContent: "center" }}
          >
            Continue to B2B quote <Arrow/>
          </button>
          {items.length > 0 && (
            <button
              type="button"
              className="quote-drawer__clear"
              onClick={() => { if (confirm("Clear all items from your quote list?")) window.__scdQuote.clear(); }}
            >
              Clear quote list
            </button>
          )}
        </footer>
      </aside>

      {/* Toast (subsequent adds) */}
      {toast && (
        <div className="quote-toast" role="status">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
            <polyline points="20 6 9 17 4 12"/>
          </svg>
          <span><strong>{toast.name}</strong> added to your quote.</span>
          <button type="button" onClick={() => { setToast(null); setOpen(true); }} className="quote-toast__link">
            View list <Arrow/>
          </button>
        </div>
      )}

      <style>{`
        .quote-backdrop {
          position: fixed; inset: 0; background: rgba(18, 25, 46, 0.42);
          opacity: 0; pointer-events: none;
          transition: opacity 280ms var(--ease-out);
          z-index: 28;
        }
        .quote-backdrop[data-open="true"] { opacity: 1; pointer-events: auto; }

        .quote-drawer {
          position: fixed; left: 0; right: 0; top: 0;
          background: var(--scd-cream-50);
          border-bottom: 1px solid var(--border);
          box-shadow: 0 24px 48px rgba(46, 34, 18, 0.16);
          z-index: 29;
          transform: translateY(-100%);
          transition: transform 320ms var(--ease-out);
          display: flex; flex-direction: column;
          max-height: 92vh;
        }
        .quote-drawer[data-open="true"] { transform: translateY(0); }
        @media (min-width: 1080px) {
          .quote-drawer { padding-top: 0; }
        }
        .quote-drawer__head {
          display: flex; align-items: flex-start; justify-content: space-between;
          gap: 16px; padding: 24px 32px 18px;
          border-bottom: 1px solid var(--border);
          background: var(--scd-cream-100);
        }
        .quote-drawer__eyebrow {
          font-family: var(--font-body); font-size: 11px; font-weight: 600;
          letter-spacing: 0.16em; text-transform: uppercase;
          color: var(--scd-blush-700); margin-bottom: 4px;
        }
        .quote-drawer__title {
          font-family: var(--font-display); font-weight: 400;
          font-size: 28px; line-height: 1.1; letter-spacing: -0.01em;
          color: var(--fg-brand); margin: 0;
          display: flex; align-items: baseline; gap: 12px; flex-wrap: wrap;
        }
        .quote-drawer__count {
          font-family: var(--font-mono); font-size: 12px;
          letter-spacing: 0.06em; color: var(--fg-muted); font-weight: 500;
        }
        .quote-drawer__close {
          width: 36px; height: 36px; border-radius: 50%;
          border: 1px solid var(--border); background: var(--scd-cream-50);
          color: var(--fg-brand); cursor: pointer;
          display: inline-flex; align-items: center; justify-content: center;
          transition: background var(--dur-fast) var(--ease-out), border-color var(--dur-fast) var(--ease-out);
        }
        .quote-drawer__close:hover {
          border-color: var(--scd-navy-800); background: var(--scd-cream-200);
        }

        .quote-drawer__body {
          flex: 1; overflow-y: auto;
          padding: 8px 32px;
        }
        @media (max-width: 640px) {
          .quote-drawer__head, .quote-drawer__body, .quote-drawer__foot { padding-left: 20px; padding-right: 20px; }
        }
        .quote-drawer__list {
          list-style: none; padding: 0; margin: 0;
          display: grid; gap: 0;
        }
        .quote-drawer__empty p {
          font-family: var(--font-display); font-style: italic;
          font-size: 17px; color: var(--fg-muted); line-height: 1.6;
          margin: 32px 0; max-width: 480px;
        }
        .quote-drawer__foot {
          padding: 20px 32px 28px;
          border-top: 1px solid var(--border);
          background: var(--scd-cream-100);
          display: grid; gap: 12px;
        }
        .quote-drawer__note {
          font-family: var(--font-display); font-style: italic;
          font-size: 14px; color: var(--fg-muted); margin: 0;
          line-height: 1.55;
        }
        .quote-drawer__clear {
          background: transparent; border: 0; padding: 0; cursor: pointer;
          font-family: var(--font-body); font-size: 12px;
          color: var(--fg-muted); justify-self: center;
          letter-spacing: 0.04em;
          border-bottom: 1px solid transparent;
          transition: color var(--dur-fast) var(--ease-out), border-color var(--dur-fast) var(--ease-out);
        }
        .quote-drawer__clear:hover {
          color: var(--scd-danger); border-bottom-color: var(--scd-danger);
        }

        /* Toast */
        .quote-toast {
          position: fixed; right: 24px; bottom: 24px; z-index: 30;
          background: var(--scd-cream-50);
          border: 1px solid var(--border); border-radius: 4px;
          box-shadow: 0 18px 40px rgba(46, 34, 18, 0.18);
          padding: 14px 18px;
          display: inline-flex; align-items: center; gap: 14px;
          font-size: 14px; color: var(--fg);
          animation: scd-toast-in 240ms var(--ease-out);
        }
        .quote-toast svg { color: var(--scd-success); flex-shrink: 0; }
        .quote-toast strong { color: var(--fg-brand); font-weight: 600; }
        .quote-toast__link {
          background: transparent; border: 0; padding: 0; cursor: pointer;
          color: var(--fg-brand); font-weight: 500; font-size: 13px;
          letter-spacing: 0.02em; font-family: var(--font-body);
          border-bottom: 1px solid var(--scd-blush-500);
          padding-bottom: 1px; margin-left: 4px;
        }
        .quote-toast__link:hover { color: var(--scd-blush-700); border-bottom-color: var(--scd-blush-700); }
        @keyframes scd-toast-in {
          from { opacity: 0; transform: translateY(8px); }
          to { opacity: 1; transform: translateY(0); }
        }
        @media (max-width: 640px) {
          .quote-toast { right: 16px; left: 16px; bottom: 16px; }
        }
      `}</style>
    </React.Fragment>
  );
}

function QuoteLine({ item }) {
  return (
    <li className="quote-line">
      <div className="quote-line__plate" aria-hidden="true">
        <svg viewBox="0 0 80 64" width="100%" height="100%">
          <rect x="10" y="40" width="60" height="8" fill="#FBF8F1" stroke="#1C2A47" strokeWidth="0.6"/>
          <rect x="6" y="34"  width="68" height="6" fill="#FBF8F1" stroke="#1C2A47" strokeWidth="0.6"/>
          <line x1="6" y1="28" x2="74" y2="28" stroke="#1C2A47" strokeWidth="1"/>
          <line x1="6" y1="32" x2="74" y2="32" stroke="#1C2A47" strokeWidth="1"/>
          <rect x="2" y="26" width="5" height="14" fill="#1C2A47"/>
          <rect x="73" y="26" width="5" height="14" fill="#1C2A47"/>
          <g transform="translate(40 16)">
            <rect x="-8" y="6" width="16" height="10" fill="#1C2A47"/>
            <circle cx="0" cy="22" r="6" fill="#FBF8F1" stroke="#1C2A47" strokeWidth="0.7"/>
          </g>
        </svg>
      </div>
      <div className="quote-line__body">
        <div className="quote-line__eyebrow">{item.eyebrow}</div>
        <div className="quote-line__name">{item.name}</div>
        <div className="quote-line__price">{item.price ? `From ${item.price}` : ""}</div>
      </div>
      <div className="quote-line__qty" role="group" aria-label={`Quantity for ${item.name}`}>
        <button onClick={() => window.__scdQuote.update(item.sku, item.qty - 1)} aria-label="Decrease quantity">−</button>
        <span aria-live="polite">{item.qty}</span>
        <button onClick={() => window.__scdQuote.update(item.sku, item.qty + 1)} aria-label="Increase quantity">+</button>
      </div>
      <button
        className="quote-line__remove"
        onClick={() => window.__scdQuote.remove(item.sku)}
        aria-label={`Remove ${item.name}`}
      >
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
      </button>
      <style>{`
        .quote-line {
          display: grid;
          grid-template-columns: 80px minmax(0, 1fr) auto auto;
          gap: 18px; align-items: center;
          padding: 18px 0;
          border-bottom: 1px solid var(--border);
        }
        .quote-line:last-child { border-bottom: 0; }
        .quote-line__plate {
          width: 80px; height: 64px;
          background: var(--scd-cream-200);
          border: 1px solid var(--border); border-radius: 3px;
          display: flex; align-items: center; justify-content: center;
        }
        .quote-line__eyebrow {
          font-family: var(--font-body); font-size: 10px; font-weight: 600;
          letter-spacing: 0.14em; text-transform: uppercase;
          color: var(--fg-muted);
        }
        .quote-line__name {
          font-family: var(--font-display); font-weight: 400;
          font-size: 18px; color: var(--fg-brand);
          letter-spacing: -0.01em; line-height: 1.2; margin-top: 2px;
        }
        .quote-line__price {
          font-size: 12px; color: var(--fg-muted); margin-top: 4px;
          font-family: var(--font-mono); letter-spacing: 0.02em;
        }
        .quote-line__qty {
          display: flex; align-items: stretch;
          border: 1px solid var(--border); border-radius: 2px;
          overflow: hidden; background: var(--scd-cream-50);
        }
        .quote-line__qty button {
          width: 30px; border: 0; background: transparent;
          color: var(--fg-brand); cursor: pointer; font-size: 16px;
          font-family: var(--font-display);
        }
        .quote-line__qty button:hover { background: var(--scd-cream-200); }
        .quote-line__qty span {
          display: inline-flex; align-items: center; justify-content: center;
          min-width: 32px; font-family: var(--font-display); font-size: 15px;
          color: var(--fg-brand);
        }
        .quote-line__remove {
          width: 30px; height: 30px; border-radius: 50%;
          border: 1px solid transparent; background: transparent;
          color: var(--fg-muted); cursor: pointer;
          display: inline-flex; align-items: center; justify-content: center;
          transition: color var(--dur-fast) var(--ease-out), border-color var(--dur-fast) var(--ease-out);
        }
        .quote-line__remove:hover { color: var(--scd-danger); border-color: var(--scd-danger); }
        @media (max-width: 640px) {
          .quote-line { grid-template-columns: 64px minmax(0, 1fr) auto; gap: 12px; }
          .quote-line__remove { grid-column: 3; grid-row: 1; align-self: start; }
          .quote-line__qty { grid-column: 2 / 4; grid-row: 2; justify-self: start; }
        }
      `}</style>
    </li>
  );
}

window.QuoteDrawer = QuoteDrawer;
