/* ============================================================
   OVERLAYS — Search + Account (header icon functions)
   ============================================================ */
function buildSearchIndex(){
  return [
    { type:"Product", title:"Mye Noir · Seaweed Caviar", sub:"Signature 50g tin · "+money(PRODUCT.basePrice), to:"/", kw:"caviar pearls seaweed signature vegan black" },
    ...BUNDLES.map(b=>({ type:"Product", title:b.name, sub:b.tins+" × 50g tin · "+money(b.price), to:"/", kw:"bundle tin pack gift "+b.use })),
    ...RECIPES.map(r=>({ type:"Recipe", title:r.title, sub:r.level+" · "+r.serves, to:"/recipes", kw:r.id+" "+r.desc+" sushi blini canapé champagne serving" })),
    { type:"Page", title:"Our Story", sub:"Maison Mye — how it began", to:"/story", kw:"about founder house history brand" },
    { type:"Page", title:"Reviews", sub:PRODUCT.reviewCount+" verified reviews", to:"/reviews", kw:"ratings testimonials stars" },
    { type:"Page", title:"Wholesale & Trade", sub:"For restaurants & events", to:"/wholesale", kw:"bulk restaurant catering chef trade samples" },
    { type:"Page", title:"How to serve", sub:"Recipes & serving ideas", to:"/recipes", kw:"sushi blini canapé champagne pairing serve" },
    { type:"Page", title:"FAQs", sub:"Serving, delivery & storage", to:"/faq", kw:"questions shipping delivery storage allergens" },
    { type:"Page", title:"Ingredients & allergens", sub:"What's inside every tin", to:"/faq", kw:"seaweed vegan allergens nutrition" },
    ...UPCOMING.map(u=>({ type:"Coming soon", title:u.name, sub:u.sub+" · "+u.eta, to:"/", kw:"collection gift "+u.sub })),
  ];
}
const POPULAR = ["Mye Noir","The Soirée","Blinis","Sushi","Our Story","Gift"];

function SearchOverlay({ open, onClose }){
  const { navigate } = useRoute();
  const [q,setQ] = useState("");
  const inputRef = useRef(null);
  const index = useRef(buildSearchIndex());

  useEffect(()=>{
    if(open){ setQ(""); setTimeout(()=>inputRef.current&&inputRef.current.focus(),120); document.body.style.overflow="hidden"; }
    else document.body.style.overflow="";
    const onKey=(e)=>{ if(e.key==="Escape") onClose(); };
    window.addEventListener("keydown",onKey);
    return ()=>window.removeEventListener("keydown",onKey);
  },[open]);

  const ql = q.trim().toLowerCase();
  const results = ql ? index.current.filter(r=> (r.title+" "+r.sub+" "+r.type+" "+(r.kw||"")).toLowerCase().includes(ql)) : [];
  const go = (to)=>{ onClose(); navigate(to); };

  return (
    <div className={"srch-root"+(open?" open":"")} aria-hidden={!open}>
      <div className="srch-scrim" onClick={onClose}></div>
      <div className="srch-panel" role="dialog" aria-label="Search">
        <div className="srch-bar wrap-wide">
          <Icon name="search" size={22} className="srch-bar-ic"/>
          <input ref={inputRef} className="srch-input" placeholder="Search Mye — products, recipes, the story…"
            value={q} onChange={e=>setQ(e.target.value)}
            onKeyDown={e=>{ if(e.key==="Enter"&&results[0]) go(results[0].to); }}/>
          <button className="srch-close" onClick={onClose} aria-label="Close search"><Icon name="close" size={20}/> <span className="hide-mob">Esc</span></button>
        </div>

        <div className="srch-body wrap-wide">
          {!ql && (
            <div className="srch-pop">
              <p className="srch-label">Popular searches</p>
              <div className="srch-chips">
                {POPULAR.map(p=>(<button key={p} className="chip" onClick={()=>setQ(p)}>{p}</button>))}
              </div>
              <div className="srch-feature">
                <Photo src={IMG.tin} label="MYE NOIR · 50G" className="srch-feature-img"/>
                <div>
                  <p className="eyebrow no-rule">The signature</p>
                  <p className="h-md" style={{marginTop:8}}>Mye Noir</p>
                  <p className="small" style={{color:"var(--ink-soft)",marginTop:8,maxWidth:"34ch"}}>Seaweed caviar with a clean ocean flavour and a delicate pop. From {money(PRODUCT.basePrice)}.</p>
                  <button className="btn btn-gold" style={{marginTop:16}} onClick={()=>go("/")}>Shop Mye Noir</button>
                </div>
              </div>
            </div>
          )}
          {ql && (
            <div className="srch-results">
              <p className="srch-label">{results.length} result{results.length!==1?"s":""} for “{q}”</p>
              {results.length===0 ? (
                <p className="srch-empty">Nothing matched. Try “blinis”, “sushi”, “gift” or “story”.</p>
              ) : results.map((r,i)=>(
                <button key={i} className="srch-result" onClick={()=>go(r.to)}>
                  <span className="srch-result-type">{r.type}</span>
                  <span style={{flex:1}}>
                    <span className="srch-result-title">{r.title}</span>
                    <span className="srch-result-sub">{r.sub}</span>
                  </span>
                  <Icon name="arrow" size={17} className="srch-result-arr"/>
                </button>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

/* ============================================================ ACCOUNT */
function AccountPanel({ open, onClose }){
  const [mode,setMode] = useState("signin"); // signin | register | track
  const [done,setDone] = useState(false);
  useEffect(()=>{
    if(open){ document.body.style.overflow="hidden"; setDone(false); }
    else document.body.style.overflow="";
    const onKey=(e)=>{ if(e.key==="Escape") onClose(); };
    window.addEventListener("keydown",onKey);
    return ()=>window.removeEventListener("keydown",onKey);
  },[open]);

  const submit = (e)=>{ e.preventDefault(); setDone(true); };

  return (
    <div className={"drawer-root acct-root"+(open?" open":"")} aria-hidden={!open}>
      <div className="drawer-scrim" onClick={onClose}></div>
      <aside className="drawer acct" role="dialog" aria-label="Account">
        <div className="drawer-head">
          <div className="row" style={{gap:10}}><Icon name="user" size={18}/><span style={{fontWeight:500,letterSpacing:".02em"}}>My account</span></div>
          <button className="hdr-ic" aria-label="Close account" onClick={onClose}><Icon name="close"/></button>
        </div>

        {done ? (
          <div className="acct-body">
            <div className="ws-sent" style={{padding:"40px 4px"}}>
              <span className="value-ic" style={{margin:"0 auto"}}><Icon name="check" size={24}/></span>
              <h3 className="h-md" style={{marginTop:18}}>{mode==="track"?"We're on it":"Welcome to Maison Mye"}</h3>
              <p style={{marginTop:10,color:"var(--ink-soft)"}}>
                {mode==="track"
                  ? "If that order exists, we've emailed its latest tracking status."
                  : "This is a demo account flow — no real account is created. Hook this up to your store backend at launch."}
              </p>
              <button className="btn btn-ghost mt-3" onClick={onClose}>Continue shopping</button>
            </div>
          </div>
        ) : (
          <div className="acct-body">
            <div className="acct-tabs">
              <button className={mode==="signin"?"on":""} onClick={()=>setMode("signin")}>Sign in</button>
              <button className={mode==="register"?"on":""} onClick={()=>setMode("register")}>Create account</button>
              <button className={mode==="track"?"on":""} onClick={()=>setMode("track")}>Track order</button>
            </div>

            {mode==="signin" && (
              <form onSubmit={submit} className="acct-form">
                <div className="field"><label>Email</label><input className="input" type="email" required placeholder="you@email.com"/></div>
                <div className="field"><label>Password</label><input className="input" type="password" required placeholder="••••••••"/></div>
                <button className="btn-link" type="button" style={{alignSelf:"flex-start"}}>Forgot password?</button>
                <button className="btn btn-gold btn-block btn-lg" type="submit">Sign in</button>
                <p className="small center" style={{color:"var(--muted)"}}>New here? <button type="button" className="acct-switch" onClick={()=>setMode("register")}>Create an account</button></p>
              </form>
            )}
            {mode==="register" && (
              <form onSubmit={submit} className="acct-form">
                <div className="field"><label>First name</label><input className="input" required placeholder="First name"/></div>
                <div className="field"><label>Email</label><input className="input" type="email" required placeholder="you@email.com"/></div>
                <div className="field"><label>Password</label><input className="input" type="password" required placeholder="Create a password"/></div>
                <label className="ws-check"><input type="checkbox" defaultChecked/> <span>Email me hosting ideas & exclusive offers</span></label>
                <button className="btn btn-gold btn-block btn-lg" type="submit">Create account</button>
                <p className="small center" style={{color:"var(--muted)"}}>By joining you agree to our <Link to="/legal/terms" onClick={onClose} style={{color:"var(--gold-3)"}}>terms</Link>.</p>
              </form>
            )}
            {mode==="track" && (
              <form onSubmit={submit} className="acct-form">
                <p className="small" style={{color:"var(--ink-soft)"}}>Enter your order number and email to see the latest status.</p>
                <div className="field"><label>Order number</label><input className="input" required placeholder="MYE-0000"/></div>
                <div className="field"><label>Email</label><input className="input" type="email" required placeholder="you@email.com"/></div>
                <button className="btn btn-gold btn-block btn-lg" type="submit">Track my order</button>
              </form>
            )}

            <div className="acct-perks">
              <span><Icon name="truck" size={14}/> Free UK delivery on selected orders</span>
              <span><Icon name="gift" size={14}/> Member-only offers</span>
              <span><Icon name="heart" size={14}/> Save your favourite bundles</span>
            </div>
          </div>
        )}
      </aside>
    </div>
  );
}

Object.assign(window, { SearchOverlay, AccountPanel });
