/* global React */
const { useState, useMemo } = React;
const { Ico, Pill, Level, product, bar, fmtKr, stockStatus, barRollup, festivalDay } = window.LagerUI;
const D = window.LAGER_DATA;

// =================== MAIN ===================
function AreaManagerApp({ countState, setCountState, profile, onLogout }) {
  const [barId, setBarId] = useState(profile?.bar_id ?? null);
  const [tab, setTab] = useState("lager");
  const [countType, setCountType] = useState("evening");
  const canSwitchBar = !profile?.bar_id;

  if (!barId) return <BarPicker onPick={id => { setBarId(id); setTab("lager"); }}/>;

  const cs = countState?.[barId];
  const eveningDone = !!cs?.evening;
  const finalDone = !!cs?.final;

  const handleSubmit = (type, data) => {
    const at = new Date().toLocaleTimeString("da-DK", { hour: "2-digit", minute: "2-digit" });
    setCountState(prev => ({
      ...prev,
      [barId]: { ...prev[barId], [type]: { by: profile?.name || bar(barId)?.responsible || "Bar-ansvarlig", at, data } },
    }));
  };

  const handleUnlock = (type) => {
    setCountState(prev => ({ ...prev, [barId]: { ...prev[barId], [type]: null } }));
  };

  return (
    <div className="area-shell">
      <AreaTopbar barId={barId} onSwitchBar={canSwitchBar ? () => setBarId(null) : null} onLogout={onLogout}/>

      <div className="area-body">
        {tab === "lager" && <AreaStockView barId={barId}/>}
        {tab === "count" && (
          <AreaCountFlow
            barId={barId}
            countType={countType}
            setCountType={setCountType}
            countState={countState}
            onSubmit={handleSubmit}
            onUnlock={handleUnlock}
          />
        )}
      </div>

      <nav className="area-tabbar">
        <button className="area-tab" aria-current={tab === "lager" ? "true" : undefined} onClick={() => setTab("lager")}>
          <Ico.bar style={{width:18, height:18}}/>
          Lagerstatus
        </button>
        <button className="area-tab" aria-current={tab === "count" ? "true" : undefined} onClick={() => setTab("count")}>
          <Ico.count style={{width:18, height:18}}/>
          Optælling
          {(eveningDone || finalDone) && <span className="area-tab-badge"/>}
        </button>
      </nav>
    </div>
  );
}

// =================== TOPBAR ===================
function AreaTopbar({ barId, onSwitchBar, onLogout }) {
  const b = bar(barId);
  const fd = festivalDay();
  return (
    <div className="area-topbar">
      <div className="brand">
        <div className="brand-mark"/>
        <div>
          <div className="brand-text">Lager</div>
          <div className="brand-sub">Bar-ansvarlig</div>
        </div>
      </div>
      <div style={{flex:1, minWidth:0, padding:"0 12px"}}>
        <div style={{fontWeight:600, fontSize:14, overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap"}}>{b?.name}</div>
        <div style={{fontSize:11, color:"var(--text-muted)"}}>{b?.location}</div>
      </div>
      <div style={{display:"flex", alignItems:"center", gap:8}}>
        <span className="day-chip"><span className="day-num">{fd.num}</span> Dag {fd.num} · {fd.name}</span>
        {onSwitchBar && (
          <button className="btn" data-size="sm" data-variant="ghost" onClick={onSwitchBar} title="Skift bar">
            <Ico.retur style={{width:13, height:13}}/>
          </button>
        )}
        {onLogout && (
          <button className="btn" data-size="sm" data-variant="ghost" onClick={onLogout}>Log ud</button>
        )}
      </div>
    </div>
  );
}

// =================== BAR PICKER ===================
function BarPicker({ onPick }) {
  const fd = festivalDay();
  return (
    <div className="area-shell">
      <div className="area-topbar">
        <div className="brand">
          <div className="brand-mark"/>
          <div>
            <div className="brand-text">Lager</div>
            <div className="brand-sub">Bar-ansvarlig</div>
          </div>
        </div>
        <span className="day-chip" style={{marginLeft:"auto"}}><span className="day-num">{fd.num}</span> Dag {fd.num} · {fd.name}</span>
      </div>
      <div className="area-body">
        <h1 style={{fontSize:22, fontWeight:600, letterSpacing:"-0.02em", margin:"4px 0 4px"}}>Vælg din bar</h1>
        <p style={{color:"var(--text-muted)", margin:"0 0 20px", fontSize:14}}>Du kan kun se og tælle den bar du er ansvarlig for.</p>
        <div style={{display:"grid", gridTemplateColumns:"repeat(auto-fill, minmax(240px, 1fr))", gap:12}}>
          {D.bars.map(b => {
            const r = barRollup(b.id);
            const tone = r.empty ? "danger" : r.low ? "warn" : "";
            return (
              <button key={b.id} className="bar-card" onClick={() => onPick(b.id)} style={{cursor:"pointer"}}>
                <div className="bar-head">
                  <span className={"bar-status " + tone}/>
                  <div style={{flex:1, minWidth:0}}>
                    <div className="bar-name">{b.name}</div>
                    <div className="bar-loc">{b.location}</div>
                  </div>
                  <Ico.arrow style={{width:16, height:16, color:"var(--text-muted)"}}/>
                </div>
                <div style={{fontSize:12, color:"var(--text-muted)", marginTop:4}}>{r.total} varelinjer · Ansv.: {b.responsible}</div>
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// =================== STOCK VIEW ===================
function AreaStockView({ barId }) {
  const rows = D.stock[barId] || [];
  const r = barRollup(barId);

  return (
    <div>
      <div style={{display:"grid", gridTemplateColumns:"repeat(3, 1fr)", gap:10, marginBottom:18}}>
        <div className="stat"><div className="stat-label">Varelinjer</div><div className="stat-value">{r.total}</div></div>
        <div className={"stat " + (r.low ? "warn" : "ok")}><div className="stat-label">Under min</div><div className="stat-value">{r.low}</div></div>
        <div className={"stat " + (r.empty ? "danger" : "ok")}><div className="stat-label">Udsolgte</div><div className="stat-value">{r.empty}</div></div>
      </div>

      <div style={{display:"flex", flexDirection:"column", gap:8}}>
        {rows.map(row => {
          const p = product(row.pid);
          const tone = stockStatus(row);
          return (
            <div key={row.pid} className={"area-stock-card " + (tone !== "ok" ? tone : "")}>
              <div style={{display:"flex", alignItems:"center", gap:10, marginBottom:6}}>
                <div style={{flex:1, minWidth:0}}>
                  <div style={{fontWeight:600, fontSize:14}}>{p.name}</div>
                  <div style={{fontSize:12, color:"var(--text-muted)"}}>{p.cat} · {p.supplier}</div>
                </div>
                <Pill tone={tone} dot>{tone === "ok" ? "OK" : tone === "warn" ? "Under min" : "Udsolgt"}</Pill>
              </div>
              <Level current={row.current} max={row.in} par={row.par}/>
              <div style={{display:"flex", justifyContent:"space-between", fontSize:12, color:"var(--text-muted)", marginTop:5}}>
                <span>Aktuelt: <b style={{color:"var(--text)"}}>{row.current}</b></span>
                <span>Min: {row.par}</span>
                <span>Modtaget: {row.in}</span>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// =================== COUNT FLOW ===================
function AreaCountFlow({ barId, countType, setCountType, countState, onSubmit, onUnlock }) {
  const cs = countState?.[barId];
  const eveningDone = !!cs?.evening;
  const finalDone = !!cs?.final;
  const isLocked = countType === "evening" ? eveningDone : finalDone;
  const submission = cs?.[countType];

  return (
    <div>
      <div style={{display:"flex", gap:4, marginBottom:16}}>
        <button className="btn" data-variant={countType === "evening" ? "primary" : "ghost"}
                onClick={() => setCountType("evening")} style={{flex:1}}>
          Aftenoptælling {eveningDone && <Ico.check style={{width:13, height:13, marginLeft:4}}/>}
        </button>
        <button className="btn" data-variant={countType === "final" ? "primary" : "ghost"}
                onClick={() => setCountType("final")} style={{flex:1}}
                disabled={!eveningDone} title={!eveningDone ? "Aftenoptælling skal indleveres først" : ""}>
          Slutoptælling {finalDone && <Ico.check style={{width:13, height:13, marginLeft:4}}/>}
        </button>
      </div>

      {isLocked ? (
        <div style={{textAlign:"center", padding:"32px 16px"}}>
          <div style={{width:60, height:60, margin:"0 auto 16px", borderRadius:"50%", background:"var(--ok-soft)", color:"var(--ok)", display:"grid", placeItems:"center"}}>
            <Ico.check style={{width:28, height:28}}/>
          </div>
          <h3 style={{margin:"0 0 6px", fontSize:18}}>{countType === "evening" ? "Aftenoptælling" : "Slutoptælling"} indleveret</h3>
          <p style={{color:"var(--text-muted)", fontSize:13, margin:"0 0 16px"}}>Indleveret af {submission?.by} kl. {submission?.at}</p>
          <button className="btn" data-variant="ghost" onClick={() => onUnlock(countType)}>Lås op og ret</button>
        </div>
      ) : (
        <AreaCountScreen
          key={countType}
          barId={barId}
          countType={countType}
          onSubmit={(data) => onSubmit(countType, data)}
        />
      )}
    </div>
  );
}

// =================== COUNT SCREEN ===================
function AreaCountScreen({ barId, countType, onSubmit }) {
  const rows = D.stock[barId] || [];
  const [counts, setCounts] = useState(() =>
    Object.fromEntries(rows.map(r => [r.pid, { full: null, open: null, spild: 0, note: "" }]))
  );
  const [confirming, setConfirming] = useState(false);

  const update = (pid, k, v) => setCounts(c => ({ ...c, [pid]: { ...c[pid], [k]: v } }));
  const filled = Object.values(counts).filter(c => c.full !== null && c.open !== null).length;
  const ready = filled === rows.length;

  const spildValue = useMemo(() =>
    rows.reduce((s, r) => s + (counts[r.pid]?.spild || 0) * (product(r.pid)?.price || 0), 0),
  [counts]);
  const spildCount = useMemo(() =>
    Object.values(counts).reduce((s, c) => s + (c.spild || 0), 0),
  [counts]);

  const typeLabel = countType === "evening" ? "Aftenoptælling" : "Slutoptælling";

  return (
    <>
      <div className="area-progress">
        <div style={{display:"flex", justifyContent:"space-between", alignItems:"center", marginBottom:6, fontSize:13}}>
          <span><b>{filled}</b> / {rows.length} varer talt</span>
          <span style={{color:"var(--text-muted)", fontSize:12}}>{ready ? "Klar til indsendelse" : `${rows.length - filled} mangler`}</span>
        </div>
        <div className="area-progress-bar"><div style={{width:`${(filled / rows.length) * 100}%`}}/></div>
      </div>

      <div className="area-instructions">
        <div className="area-instruction">
          <div className="area-instruction-num">1</div>
          <div>
            <div style={{fontWeight:500, marginBottom:2}}>Tæl <b>hele</b> ubrudte enheder</div>
            <div style={{color:"var(--text-muted)", fontSize:12}}>Fustager ikke sat på, flasker med ubrudt prop, uåbnede kasser</div>
          </div>
        </div>
        <div className="area-instruction">
          <div className="area-instruction-num">2</div>
          <div>
            <div style={{fontWeight:500, marginBottom:2}}>Tæl <b>anbrud</b> (åbnede)</div>
            <div style={{color:"var(--text-muted)", fontSize:12}}>Fustager på hanen, åbnede flasker, kasser der er i gang</div>
          </div>
        </div>
      </div>

      {spildCount > 0 && (
        <div className="spild-banner">
          <div className="spild-icon"><Ico.warn style={{width:18, height:18}}/></div>
          <div style={{flex:1}}>
            <div style={{fontSize:13, fontWeight:600}}>Spild registreret</div>
            <div style={{fontSize:12, color:"var(--text-muted)", marginTop:2}}>
              {spildCount} enheder · {Object.values(counts).filter(c=>c.spild>0).length} varer
            </div>
          </div>
          <div className="spild-value">
            <div className="spild-value-label">Værdi</div>
            <div className="spild-value-num">{fmtKr(spildValue)}</div>
          </div>
        </div>
      )}

      <div className="area-cards">
        {rows.map(row => {
          const p = product(row.pid);
          const v = counts[row.pid];
          const done = v.full !== null && v.open !== null;
          return (
            <div key={row.pid} className={"area-card " + (done ? "done" : "")}>
              <div className="area-card-head">
                <div>
                  <div className="area-card-name">{p.name}</div>
                  <div className="area-card-cat">{p.cat} · {p.unit}</div>
                </div>
                {done && <div className="area-card-check"><Ico.check style={{width:14, height:14}}/></div>}
              </div>
              <div className="area-card-fields">
                <AreaCountField label="Hele (retur)" value={v.full} onChange={(n) => update(row.pid, "full", n)} accent/>
                <AreaCountField label="Anbrud" value={v.open} onChange={(n) => update(row.pid, "open", n)}/>
              </div>
              <div className="area-card-spild">
                <div className="area-card-spild-label">
                  <Ico.warn style={{width:13, height:13, color: v.spild > 0 ? "var(--warn)" : "var(--text-faint)"}}/>
                  <span>Spild</span>
                  {v.spild > 0 && <span className="area-card-spild-cost">≈ {fmtKr(v.spild * (p.price || 0))}</span>}
                </div>
                <div className="area-card-spild-input">
                  <button type="button" onClick={() => update(row.pid, "spild", Math.max(0, (v.spild || 0) - 1))}>−</button>
                  <input type="text" inputMode="numeric" value={v.spild || 0}
                         onChange={e => { const n = parseInt(e.target.value.replace(/\D/g, ""), 10); update(row.pid, "spild", isNaN(n) ? 0 : n); }}/>
                  <button type="button" onClick={() => update(row.pid, "spild", (v.spild || 0) + 1)}>+</button>
                </div>
              </div>
              <input className="input" placeholder="Note (valgfri) — fx. utæt fustage, spild…"
                     value={v.note} onChange={e => update(row.pid, "note", e.target.value)}
                     style={{marginTop:8, fontSize:12.5}}/>
            </div>
          );
        })}
      </div>

      <div className="area-footer">
        <div style={{flex:1, fontSize:13, color:"var(--text-muted)"}}>
          {ready ? "Alle varer er talt op ✓" : `${rows.length - filled} varer mangler endnu`}
        </div>
        <button className="btn" data-variant="primary" data-size="lg"
                disabled={!ready}
                style={{opacity: ready ? 1 : 0.5, cursor: ready ? "pointer" : "not-allowed"}}
                onClick={() => setConfirming(true)}>
          <Ico.check style={{width:14, height:14}}/> Indsend {typeLabel.toLowerCase()}
        </button>
      </div>

      {confirming && (
        <div className="confirm-overlay">
          <div className="confirm-box">
            <h3 style={{margin:"0 0 8px"}}>Indsend {typeLabel.toLowerCase()}?</h3>
            <p style={{color:"var(--text-muted)", fontSize:13, margin:0}}>Optællingen låses og sendes til lager-ansvarlig.</p>
            <div style={{display:"flex", gap:8, justifyContent:"flex-end", marginTop:20}}>
              <button className="btn" data-variant="ghost" onClick={() => setConfirming(false)}>Annuller</button>
              <button className="btn" data-variant="primary" onClick={() => { onSubmit(counts); setConfirming(false); }}>
                <Ico.check style={{width:13, height:13}}/> Ja, indsend og lås
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}

// =================== REUSABLE ===================
function AreaCountField({ label, value, onChange, accent }) {
  return (
    <div className={"area-field " + (accent ? "accent" : "")}>
      <div className="area-field-label">{label}</div>
      <div className="area-field-input">
        <button type="button" onClick={() => onChange(Math.max(0, (value || 0) - 1))}>−</button>
        <input type="text" inputMode="numeric" placeholder="—"
               value={value === null ? "" : value}
               onChange={e => {
                 const v = e.target.value === "" ? null : parseInt(e.target.value.replace(/\D/g, ""), 10);
                 onChange(isNaN(v) ? null : v);
               }}/>
        <button type="button" onClick={() => onChange((value || 0) + 1)}>+</button>
      </div>
    </div>
  );
}

window.LagerAreaApp = AreaManagerApp;
