const { useState, useEffect, useRef, useCallback } = React;

const BrandLogo = ({right=null}) => (
  <div className="card__brand">
    <img src={`${window.LH_PREFIX}/lh-logo.svg`} className="card__brand-logo" alt="Lev Haolam" height="30" style={{width:"auto",display:"block"}}/>
    {right}
  </div>
);

const PILL_LABEL = { green: "On track", yellow: "Needs attention", gray: "Inactive" };

const StatusPill = ({tone}) => {
  const palette = {
    green:  {bg:"#E8F3CF", fg:"#3F5810", dot:"#81AC22"},
    yellow: {bg:"#FFEFD2", fg:"#7A4A06", dot:"#E0901C"},
    gray:   {bg:"#EEEFF1", fg:"#41474F", dot:"#A9ACB4"}
  }[tone] || {bg:"#EEEFF1", fg:"#41474F", dot:"#A9ACB4"};
  const label = PILL_LABEL[tone] || PILL_LABEL.gray;
  return (
    <span className="pill" style={{padding:"6px 13px", background:palette.bg, color:palette.fg, fontSize:13}}>
      <span className="pill__dot" style={{
        width:8, height:8, background:palette.dot,
        boxShadow: tone==="green" ? "0 0 0 3px rgba(129,172,34,0.18)" : tone==="yellow" ? "0 0 0 3px rgba(224,144,28,0.18)" : "none"
      }}/>
      {label}
    </span>
  );
};

const STEPS = [
  {key:"label",   label:"Preparing in warehouse"},
  {key:"picked",  label:"Picked up"},
  {key:"transit", label:"In transit"},
  {key:"done",    label:"Delivered"}
];

const StepRail = ({stage, tone="green", terminal}) => {
  const stepStates = STEPS.map((_, i) => {
    if (terminal === "canceled" || stage === null || stage === undefined) return "pending";
    if (i < stage) return "done";
    if (i === stage) return stage === 3 ? "done" : "current";
    return "pending";
  });
  const currentColor = tone==="yellow" ? "#E0901C" : tone==="gray" ? "#A9ACB4" : "#FE8A20";
  const doneColor = terminal==="canceled" ? "#C8CACE" : "#81AC22";
  const pendingColor = "#DFDFE1";

  const lastDone = stepStates.lastIndexOf("done");
  const cur = stepStates.indexOf("current");
  const denom = STEPS.length - 1;
  const widthPct = cur >= 0 ? (cur/denom)*100 : (lastDone===STEPS.length-1 ? 100 : Math.max(lastDone,0)/denom * 100);

  return (
    <div className="rail" role="list" aria-label="Shipment progress">
      <div className="rail__track">
        {(lastDone >= 0 || cur >= 0) && (
          <div className="rail__fill" style={{width:`${Math.max(0,widthPct)}%`, background:doneColor}}/>
        )}
      </div>
      <div className="rail__dots" style={{"--n":STEPS.length}}>
        {STEPS.map((s, i) => {
          const st = stepStates[i];
          const isCurrent = st === "current";
          const isDone = st === "done";
          const dotColor = terminal==="canceled" ? pendingColor : isCurrent ? currentColor : isDone ? doneColor : pendingColor;
          const labelColor = terminal==="canceled" ? "#A9ACB4" : st==="pending" ? "#A9ACB4" : "#202327";
          const glow = isCurrent ? `0 0 0 4px ${tone==="yellow" ? "rgba(224,144,28,0.18)" : tone==="gray" ? "rgba(169,172,180,0.22)" : "rgba(254,138,32,0.18)"}` : "none";
          return (
            <div key={s.key} className={`rail__node rail__node--${st}`} role="listitem" aria-current={isCurrent ? "step" : undefined}>
              <div className="rail__dot" style={{background:dotColor, boxShadow:glow}}>
                {isDone && !isCurrent && (
                  <svg width="10" height="10" viewBox="0 0 10 10"><path d="M2 5.2L4.2 7.4L8 3" fill="none" stroke="#FFFFFF" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"/></svg>
                )}
                {isCurrent && <span className="rail__inner"/>}
              </div>
              <div className="rail__label" style={{color:labelColor, fontWeight: isCurrent ? 700 : 500}}>{s.label}</div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

const EventsList = ({events}) => (
  <ol className="evlist">
    {events.map((e, i) => (
      <li key={i} className={`ev ${i===0 ? "ev--head" : ""}`}>
        <div className="ev__rail"><span className="ev__dot"/></div>
        <div className="ev__when">
          <div className="ev__date">{e.date}</div>
          <div className="ev__time">{e.time}</div>
        </div>
        <div className="ev__what">
          <div className="ev__desc">{e.desc}</div>
          <div className="ev__where">{e.place}</div>
        </div>
      </li>
    ))}
  </ol>
);

const ERRORS = {
  empty:       { title:"Please enter a tracking number.",
                 body:"You'll find it in the shipping confirmation we sent by email." },
  not_found:   { title:"That doesn't look like one of our tracking numbers.",
                 body:"Please double-check the digits in your confirmation email. If it still doesn't work, email us and we'll verify it for you.",
                 showSupport:true },
  rate_limit:  { title:"Too many lookups from this device.",
                 body:"Please wait a minute before trying again." },
  unavailable: { title:"Tracking is temporarily unavailable.",
                 body:"Our carrier feed is having a moment. Try again in a few minutes. If this keeps happening, email us.",
                 showSupport:true }
};

function InputView({onSubmit, prefill="", initialError=null}) {
  const [val, setVal] = useState(prefill);
  const [err, setErr] = useState(initialError);
  const inputRef = useRef(null);
  useEffect(() => { inputRef.current && inputRef.current.focus(); }, []);
  useEffect(() => { setErr(initialError); }, [initialError]);

  function submit(e) {
    e.preventDefault();
    const v = val.trim();
    if (!v) { setErr("empty"); return; }
    setErr(null);
    onSubmit(v);
  }
  const error = err ? ERRORS[err] : null;

  return (
    <section className="card card--input" aria-labelledby="track-h">
      <BrandLogo/>
      <div className="card__kicker">
        <span className="kicker__dot"/> Track your Lev Haolam box
      </div>
      <h1 id="track-h" className="card__h">Where is my box?</h1>
      <p className="card__sub">Enter your tracking number. You'll find it in the shipping confirmation we sent by email.</p>
      <form className="trackform" onSubmit={submit} noValidate>
        <label className="trackform__label" htmlFor="tracking-input">Tracking number</label>
        <div className={`trackform__row ${err ? "trackform__row--err" : ""}`}>
          <input ref={inputRef} id="tracking-input" className="trackform__input" type="text" inputMode="text" autoComplete="off" spellCheck="false"
            placeholder="Your tracking number" value={val} onChange={(e) => {setVal(e.target.value); if (err) setErr(null);}}
            aria-invalid={!!err} aria-describedby={err ? "tracking-err" : undefined}/>
          <button type="submit" className="trackform__btn">
            <span>Track shipment</span>
            <svg width="14" height="14" viewBox="0 0 14 14" aria-hidden="true"><path d="M1 7h11M8 3l4 4-4 4" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </button>
        </div>
        {error && (
          <div id="tracking-err" className="trackform__err" role="alert">
            <svg width="18" height="18" viewBox="0 0 18 18" className="trackform__erricon" aria-hidden="true">
              <circle cx="9" cy="9" r="8" fill="none" stroke="currentColor" strokeWidth="1.4"/>
              <circle cx="9" cy="13" r="1" fill="currentColor"/>
              <path d="M9 4.5v5.5" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/>
            </svg>
            <div>
              <div className="trackform__errtitle">{error.title}</div>
              <div className="trackform__errbody">{error.body}</div>
              {error.showSupport && (
                <a className="trackform__errcta" href="mailto:support@levhaolam.com?subject=Tracking%20number%20help">
                  <svg width="14" height="14" viewBox="0 0 14 14" aria-hidden="true"><path d="M1.5 3.5h11v7h-11zM1.5 3.5l5.5 4 5.5-4" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round" strokeLinecap="round"/></svg>
                  <span>Email support@levhaolam.com</span>
                </a>
              )}
            </div>
          </div>
        )}
        <div className="trackform__help">
          Lost your number? <a href="mailto:support@levhaolam.com">Email support</a>.
        </div>
      </form>
    </section>
  );
}

function LoadingView({tracking}) {
  return (
    <section className="card card--loading" aria-busy="true" aria-live="polite">
      <BrandLogo/>
      <div className="skel__row">
        <div className="skel__block" style={{width:180, height:20}}/>
        <div className="skel__block" style={{width:120, height:32, borderRadius:999}}/>
      </div>
      <div className="skel__block" style={{width:"70%", height:18, marginTop:18}}/>
      <div className="skel__block" style={{width:"55%", height:18, marginTop:8}}/>
      <div className="skel__rail">
        <div className="skel__track"/>
        <div className="skel__dots">
          {[0,1,2,3].map(i => <div key={i} className="skel__dot"/>)}
        </div>
      </div>
      <div className="skel__row" style={{marginTop:28}}>
        <div className="skel__block" style={{width:220, height:16}}/>
        <div className="skel__block" style={{width:120, height:14}}/>
      </div>
      <div className="loading-note">Looking up <span className="loading-note__code">{tracking}</span>…</div>
    </section>
  );
}

function ResultView({tracking, apiData, onReset}) {
  const [open, setOpen] = useState(false);
  if (!apiData) return null;

  const statusKey = apiData.status_key;
  const status = window.LH_STATUSES[statusKey] || window.LH_STATUSES.in_transit;
  const tone = apiData.color || status.tone;
  const label = apiData.customer_label || status.label;
  const explanation = apiData.explanation || status.explanation;
  const events = transformEvents(apiData.raw_events);
  const lastUpdated = formatLastUpdate(apiData.last_update);

  const showRail = status.stage !== null && status.stage !== undefined;
  const showEvents = status.stage >= 2 && events.length > 0;
  const showUpdated = !!apiData.last_update;
  const isAlert = tone === "yellow";
  const supportCta = (
    <a className={`card__supportcta ${isAlert ? "card__supportcta--alert" : ""}`} href="mailto:support@levhaolam.com?subject=Help%20with%20my%20tracking">
      <svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><path d="M2 4h12v8H2zM2 4l6 4.5L14 4" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round" strokeLinecap="round"/></svg>
      <div className="card__supportcta__text">
        <strong>Something doesn't look right?</strong>
        <span>Email support@levhaolam.com and we'll look into it personally.</span>
      </div>
      <svg className="card__supportcta__chev" width="14" height="14" viewBox="0 0 14 14" aria-hidden="true"><path d="M5 3l4 4-4 4" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>
    </a>
  );

  return (
    <section className={`card card--result ${isAlert ? "card--alert" : ""}`} aria-labelledby="res-h">
      <BrandLogo right={<StatusPill tone={tone}/>}/>
      <div className="card__top">
        <div>
          <div className="card__codeLabel">Tracking number</div>
          <div className="card__code">
            <span>{tracking}</span>
            <button className="copybtn" aria-label="Copy tracking number" onClick={() => navigator.clipboard && navigator.clipboard.writeText(tracking)}>
              <svg width="14" height="14" viewBox="0 0 14 14" aria-hidden="true">
                <rect x="3.5" y="3.5" width="7" height="8" rx="1.5" fill="none" stroke="currentColor" strokeWidth="1.2"/>
                <rect x="1.5" y="1.5" width="7" height="8" rx="1.5" fill="none" stroke="currentColor" strokeWidth="1.2" opacity="0.55"/>
              </svg>
            </button>
          </div>
        </div>
      </div>

      <h1 id="res-h" className="card__h card__h--sm">
        {isAlert && (<svg className="card__warn" width="22" height="22" viewBox="0 0 22 22" aria-hidden="true"><path d="M11 3L1.5 19.5h19L11 3z" fill="none" stroke="#E0901C" strokeWidth="1.8" strokeLinejoin="round"/><path d="M11 9v4.6" stroke="#E0901C" strokeWidth="1.8" strokeLinecap="round"/><circle cx="11" cy="16.4" r="0.7" fill="#E0901C"/></svg>)}
        {label}
      </h1>

      {explanation && (
        <p className="card__explain">
          {explanation}
        </p>
      )}

      {isAlert && supportCta}

      {showRail && (
        <div className="card__rail">
          <StepRail stage={status.stage} tone={tone} terminal={status.terminal}/>
        </div>
      )}

      {!isAlert && supportCta}

      {showUpdated && (
        <div className="card__updated">
          <svg width="13" height="13" viewBox="0 0 13 13" aria-hidden="true"><circle cx="6.5" cy="6.5" r="5.5" fill="none" stroke="currentColor" strokeWidth="1.1"/><path d="M6.5 3.5v3.2l2 1.3" fill="none" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round"/></svg>
          <span>Updated {lastUpdated}</span>
        </div>
      )}

      {showEvents && (
        <>
          <button className={`evbtn ${open ? "evbtn--open" : ""}`} onClick={() => setOpen(o => !o)} aria-expanded={open}>
            <div className="evbtn__l">
              <div className="evbtn__icon" aria-hidden="true">
                <svg width="18" height="18" viewBox="0 0 18 18"><path d="M3 5h12M3 9h12M3 13h8" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>
              </div>
              <div>
                <div className="evbtn__title">{open ? "Hide detailed delivery history" : "View detailed delivery history"}</div>
                <div className="evbtn__sub">{events.length} carrier updates, newest first</div>
              </div>
            </div>
            <svg width="14" height="14" viewBox="0 0 14 14" className="evbtn__chev" aria-hidden="true"><path d="M3 5l4 4 4-4" stroke="currentColor" strokeWidth="1.7" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </button>
          <div className={`evdrawer ${open ? "evdrawer--open" : ""}`} aria-hidden={!open}>
            <div><EventsList events={events}/></div>
          </div>
        </>
      )}

      <button className="trackanother" onClick={onReset}>
        <svg width="15" height="15" viewBox="0 0 15 15" aria-hidden="true"><path d="M6 2.5L2 6.5l4 4M2.5 6.5H10a3 3 0 0 1 3 3v0" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
        <span>Track another shipment</span>
      </button>
    </section>
  );
}

function readInitialTracking() {
  const m = window.location.pathname.match(/\/tracking\/([^/?#]+)/i);
  if (m && m[1]) { try { return decodeURIComponent(m[1]); } catch (_) { return m[1]; } }
  return new URLSearchParams(window.location.search).get("tracking") || "";
}

function App() {
  const initialTracking = readInitialTracking();
  const [view, setView]       = useState(() => initialTracking ? "loading" : "input");
  const [tracking, setTracking] = useState(initialTracking || "");
  const [apiData, setApiData] = useState(null);
  const [errorKey, setErrorKey] = useState(null);

  const runFetch = useCallback(async (raw) => {
    const result = await fetchTracking(raw);
    if (result.ok && result.data._trace) {
      console.groupCollapsed(`[tracker] ${raw}`);
      result.data._trace.forEach(e => console.log(`+${e.ms}ms`, e.event, e));
      console.groupEnd();
    }
    if (!result.ok) {
      setErrorKey(result.errorKey);
      setApiData(null);
      setView("input");
      return;
    }
    setApiData(result.data);
    setErrorKey(null);
    setView("result");
  }, []);

  useEffect(() => {
    if (initialTracking) runFetch(initialTracking);
  }, []);

  const onSubmit = useCallback((v) => {
    setTracking(v);
    setView("loading");
    setApiData(null);
    setErrorKey(null);
    if (window.LH_PREFIX) window.history.pushState({}, "", "/tracking/" + encodeURIComponent(v));
    runFetch(v);
  }, [runFetch]);

  const onReset = useCallback(() => {
    setApiData(null);
    setErrorKey(null);
    setTracking("");
    setView("input");
    if (window.LH_PREFIX) window.history.pushState({}, "", "/tracking");
  }, []);

  return (
    <div className="page">
      <main className="stage">
        {view === "input"   && <InputView   onSubmit={onSubmit} prefill={tracking} initialError={errorKey}/>}
        {view === "loading" && <LoadingView tracking={tracking}/>}
        {view === "result"  && <ResultView  tracking={tracking} apiData={apiData} onReset={onReset}/>}
      </main>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App/>);