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

// =================== CREDIT NOTES ===================
function CreditNotesScreen({ go, notesList, setNotesList }) {
  const [openId, setOpenId] = useState(D.creditNotes[1].id);
  const open = notesList.find(c => c.id === openId);

  const totalDiff = useMemo(() => {
    let bad = 0;
    notesList.forEach(c => c.lines.forEach(l => { if (!l.ok) bad++; }));
    return bad;
  }, [notesList]);

  return (
    <>
      <div className="page-header">
        <div>
          <h1 className="page-title">Kreditnotaer</h1>
          <p className="page-sub">PDF-kreditnotaer indlæses og krydstjekkes automatisk mod jeres egne retur-tal.</p>
        </div>
        <div className="page-actions">
          <button className="btn"><Ico.upload style={{width:14,height:14}}/> Upload PDF</button>
        </div>
      </div>

      <div className="page-body">
        <div className="grid grid-4">
          <Stat label="Modtaget" value={notesList.length} delta={`fra ${new Set(notesList.map(c=>c.supplier)).size} leverandører`}/>
          <Stat label="Matchet 100%" value={notesList.filter(c=>c.status==="matched").length} tone="ok" delta="Klar til bogføring"/>
          <Stat label="Afvigelser" value={totalDiff} tone="warn" delta="Kræver godkendelse"/>
          <Stat label="Afventer leverandør" value={notesList.filter(c=>c.status==="pending").length} delta="Reklamation afsendt"/>
        </div>

        <div className="cn-layout">
          {/* List */}
          <div className="card" style={{overflow:"hidden"}}>
            <div className="card-head"><h3 className="card-title">Indbakke</h3></div>
            <div>
              {notesList.map(c => {
                const bad = c.lines.filter(l => !l.ok).length;
                const tone = c.status === "matched" || c.status === "booked" ? "ok" : c.status === "discrepancy" ? "warn" : "info";
                const pillLabel = c.status === "booked" ? "Bogført" : c.status === "matched" ? "Match" : c.status === "discrepancy" ? `${bad} afv.` : "Afventer";
                return (
                  <button key={c.id} onClick={() => setOpenId(c.id)}
                          style={{
                            display:"block", width:"100%", textAlign:"left",
                            padding:"12px 14px",
                            borderBottom:"1px solid var(--border)",
                            background: c.id === openId ? "var(--bg-hover)" : "transparent",
                            border:0, borderLeft: c.id === openId ? "2px solid var(--accent)" : "2px solid transparent",
                            cursor:"pointer"
                          }}>
                    <div style={{display:"flex", alignItems:"center", gap:8, marginBottom:4}}>
                      <Ico.doc style={{width:14,height:14, color:"var(--text-muted)"}}/>
                      <span style={{fontWeight:500, fontSize:13}}>{c.supplier}</span>
                      <Pill tone={tone} dot>{pillLabel}</Pill>
                    </div>
                    <div style={{fontSize:12, color:"var(--text-muted)", fontFamily:"var(--mono)"}}>{c.id}</div>
                    <div style={{fontSize:12, color:"var(--text-muted)", marginTop:2}}>{c.date} · {c.lines.length} linjer</div>
                  </button>
                );
              })}
            </div>
          </div>

          {/* Detail with side-by-side recon */}
          <div className="card" style={{overflow:"hidden"}}>
            <div className="card-head">
              <Ico.doc style={{width:14,height:14}}/>
              <h3 className="card-title">{open.supplier} · {open.id}</h3>
              <span className="muted" style={{fontSize:12}}>{open.pdfName}</span>
              <span style={{marginLeft:"auto", display:"flex", gap:6}}>
                <button className="btn" data-size="sm" data-variant="ghost">Vis PDF</button>
                {open.status === "discrepancy" && (
                  <>
                    <button className="btn" data-size="sm">Send reklamation</button>
                    <button className="btn" data-size="sm" data-variant="primary"
                            onClick={() => setNotesList(l => l.map(c => c.id === open.id ? { ...c, status: "matched" } : c))}>
                      <Ico.check style={{width:13,height:13}}/> Godkend afvigelse
                    </button>
                  </>
                )}
                {open.status === "matched" && (
                  <button className="btn" data-size="sm" data-variant="primary"
                          onClick={() => setNotesList(l => l.map(c => c.id === open.id ? { ...c, status: "booked" } : c))}>
                    <Ico.check style={{width:13,height:13}}/> Bogfør
                  </button>
                )}
                {open.status === "booked" && (
                  <span style={{fontSize:13, color:"var(--ok)", fontWeight:500}}>Bogført</span>
                )}
              </span>
            </div>

            <div style={{padding:"12px 16px", display:"flex", gap:18, fontSize:13, borderBottom:"1px solid var(--border)", background:"var(--bg-sunken)"}}>
              <span><span className="muted">Reference:</span> {open.reference}</span>
              <span><span className="muted">Dato:</span> {open.date}</span>
              <span><span className="muted">Linjer:</span> {open.lines.length}</span>
              <span><span className="muted">Status:</span> <Pill tone={open.status === "matched" ? "ok" : open.status === "discrepancy" ? "warn" : "info"} dot>{open.status === "matched" ? "Fuld match" : open.status === "discrepancy" ? "Afvigelse" : "Afventer"}</Pill></span>
            </div>

            <div className="recon">
              <div className="recon-side">
                <h4>📄 Fra leverandør (PDF)</h4>
                {open.lines.map((l, i) => (
                  <div key={i} className={"match-line " + (!l.ok ? "bad" : "")}>
                    <div>
                      <div style={{fontWeight:500}}>{l.desc}</div>
                      <div className="muted" style={{fontSize:11, fontFamily:"var(--mono)"}}>{l.pid}</div>
                    </div>
                    <div className="num">{l.theirQty} stk</div>
                    <div className="num">{fmtKr(l.theirQty * l.theirPrice)}</div>
                  </div>
                ))}
              </div>
              <div className="recon-side">
                <h4>🍺 Vores retur-opgørelse</h4>
                {open.lines.map((l, i) => (
                  <div key={i} className={"match-line " + (!l.ok ? "bad" : "")}>
                    <div>
                      <div style={{fontWeight:500}}>{product(l.pid)?.name || l.pid}</div>
                      <div className="muted" style={{fontSize:11}}>
                        {l.ok ? <><Ico.check style={{width:11,height:11,verticalAlign:"middle"}}/> Stemmer</> : <>⚠ Δ {l.delta} stk</>}
                      </div>
                    </div>
                    <div className="num">{l.ourQty} stk</div>
                    <div className="num">{fmtKr(l.ourQty * l.theirPrice)}</div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

// =================== DISCREPANCIES ===================
function DiscrepanciesScreen({ go, notesList, setNotesList }) {
  const items = useMemo(() => {
    const out = [];
    notesList.forEach(c => c.lines.forEach(l => {
      if (!l.ok) out.push({ cn: c, line: l });
    }));
    return out;
  }, [notesList]);

  return (
    <>
      <div className="page-header">
        <div>
          <h1 className="page-title">Afvigelser</h1>
          <p className="page-sub">Uoverensstemmelser mellem kreditnotaer og egne retur-tal — kræver godkendelse.</p>
        </div>
        <div className="page-actions">
          <button className="btn"><Ico.upload style={{width:14,height:14}}/> Eksportér rapport</button>
        </div>
      </div>

      <div className="page-body">
        <div className="card" style={{overflow:"hidden"}}>
          <table className="tbl">
            <thead>
              <tr>
                <th>Vare</th>
                <th>Leverandør</th>
                <th>Kreditnota</th>
                <th className="num">Vores tal</th>
                <th className="num">Leverandør tal</th>
                <th className="num">Δ</th>
                <th className="num">Værdi af afv.</th>
                <th>Handling</th>
              </tr>
            </thead>
            <tbody>
              {items.map((x, i) => {
                const valueDiff = (x.line.ourQty - x.line.theirQty) * x.line.theirPrice;
                return (
                  <tr key={i}>
                    <td style={{fontWeight:500}}>{product(x.line.pid)?.name}</td>
                    <td className="muted">{x.cn.supplier}</td>
                    <td className="muted" style={{fontFamily:"var(--mono)", fontSize:12}}>{x.cn.id}</td>
                    <td className="num">{x.line.ourQty}</td>
                    <td className="num">{x.line.theirQty}</td>
                    <td className="num" style={{color:"var(--danger)", fontWeight:600}}>{x.line.delta}</td>
                    <td className="num" style={{color: valueDiff > 0 ? "var(--danger)" : ""}}>{fmtKr(Math.abs(valueDiff))}</td>
                    <td>
                      <div style={{display:"flex", gap:6}}>
                        <button className="btn" data-size="sm" data-variant="ghost">Reklamér</button>
                        <button className="btn" data-size="sm"
                                onClick={() => setNotesList(prev => prev.map(c => {
                                  if (c.id !== x.cn.id) return c;
                                  const updatedLines = c.lines.map(ll => ll === x.line ? { ...ll, ok: true, delta: 0 } : ll);
                                  return { ...c, lines: updatedLines, status: updatedLines.every(ll => ll.ok) ? "matched" : c.status };
                                }))}>
                          Godkend
                        </button>
                      </div>
                    </td>
                  </tr>
                );
              })}
              {items.length === 0 && (
                <tr><td colSpan={8} style={{textAlign:"center", padding:40, color:"var(--text-muted)"}}>Ingen afvigelser — alt stemmer ✓</td></tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </>
  );
}

// =================== SETTINGS ===================
const CATALOG_SHEET_NAMES = ['sortiment', 'produkter', 'products', 'katalog', 'catalog', 'leverandør', 'leverandorer', 'leverandørliste', 'supplier', 'suppliers'];

function detectSheetType(sheetName) {
  const n = sheetName.toLowerCase().trim();
  return CATALOG_SHEET_NAMES.some(c => n.includes(c)) ? 'catalog' : 'bar';
}

function detectImportColumns(headers) {
  const h = (headers || []).map(x => String(x || '').toLowerCase().trim());
  const find = (...kws) => h.findIndex(col => kws.some(k => col.includes(k)));
  return {
    nameCol:     find('produkt', 'navn', 'betegnelse', 'vare', 'product'),
    qtyCol:      find('antal', 'beholdning', 'start', 'mængde', 'qty', 'quantity'),
    supplierCol: find('leverandør', 'leverandor', 'supplier'),
    priceCol:    find('pris', 'price', 'kostpris', 'enhedspris'),
    categoryCol: find('kategori', 'category', 'type', 'gruppe'),
    unitCol:     find('enhed', 'unit'),
  };
}

function parseImportSheet(ws, sheetName) {
  const rows = XLSX.utils.sheet_to_json(ws, { header: 1, defval: '' });
  const type = detectSheetType(sheetName);
  if (!rows.length) return { name: sheetName, type, products: [] };
  const cols = detectImportColumns(rows[0]);
  const nameIdx = cols.nameCol >= 0 ? cols.nameCol : 0;
  const qtyIdx  = cols.qtyCol  >= 0 ? cols.qtyCol  : 1;
  const products = [];
  for (let i = 1; i < rows.length; i++) {
    const row = rows[i];
    const name = String(row[nameIdx] || '').trim();
    if (!name) continue;
    products.push({
      name,
      qty:      parseInt(row[qtyIdx]) || 0,
      supplier: cols.supplierCol >= 0 ? String(row[cols.supplierCol] || '').trim() : '',
      price:    cols.priceCol    >= 0 ? (parseFloat(String(row[cols.priceCol]).replace(',', '.')) || 0) : 0,
      category: cols.categoryCol >= 0 ? String(row[cols.categoryCol] || '').trim() : '',
      unit:     cols.unitCol     >= 0 ? String(row[cols.unitCol] || '').trim() : 'stk',
    });
  }
  return { name: sheetName, type, products };
}

function ImportSection({ profile }) {
  const [status, setStatus] = useState('idle');
  const [preview, setPreview] = useState(null);
  const [errorMsg, setErrorMsg] = useState('');

  const handleFile = (e) => {
    const file = e.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (evt) => {
      try {
        const wb = XLSX.read(new Uint8Array(evt.target.result), { type: 'array' });
        const sheets = wb.SheetNames
          .map(name => parseImportSheet(wb.Sheets[name], name))
          .filter(s => s.products.length > 0);
        const bars = sheets.filter(s => s.type === 'bar');
        const catalogs = sheets.filter(s => s.type === 'catalog');
        setPreview({ bars, catalogs });
        setStatus('preview');
      } catch (err) {
        setErrorMsg('Kunne ikke læse filen: ' + err.message);
        setStatus('error');
      }
    };
    reader.readAsArrayBuffer(file);
  };

  const handleSave = async () => {
    setStatus('saving');
    try {
      const orgId = profile?.org_id;
      if (!orgId) throw new Error('Ingen org_id på profilen — kør SQL-migrationen først.');
      const sb = window.supabaseClient;

      await sb.from('inventory').delete().eq('org_id', orgId);
      await sb.from('bars').delete().eq('org_id', orgId);
      await sb.from('products').delete().eq('org_id', orgId);

      // Collect all unique products from both bar sheets and catalog sheets
      const productMap = new Map();
      const allSheets = [...(preview.catalogs || []), ...(preview.bars || [])];
      allSheets.forEach(sheet => sheet.products.forEach(p => {
        if (!productMap.has(p.name)) productMap.set(p.name, {
          org_id: orgId, name: p.name,
          category: p.category, unit: p.unit || 'stk',
          supplier: p.supplier, price: p.price,
        });
      }));

      const { data: insertedProducts, error: pe } = await sb
        .from('products').insert([...productMap.values()]).select();
      if (pe) throw pe;
      const productIdMap = new Map(insertedProducts.map(p => [p.name, p.id]));

      // Only create bars and inventory rows for bar-type sheets
      if (preview.bars.length > 0) {
        const { data: insertedBars, error: be } = await sb
          .from('bars')
          .insert(preview.bars.map((b, i) => ({ org_id: orgId, name: b.name, sort_order: i })))
          .select();
        if (be) throw be;
        const barIdMap = new Map(insertedBars.map(b => [b.name, b.id]));

        const invRows = [];
        preview.bars.forEach(bar => {
          const barId = barIdMap.get(bar.name);
          bar.products.forEach(p => {
            const productId = productIdMap.get(p.name);
            if (barId && productId) invRows.push({
              org_id: orgId, bar_id: barId, product_id: productId,
              start_qty: p.qty, current_qty: p.qty, par_qty: 0, target_qty: p.qty,
            });
          });
        });

        const { error: ie } = await sb.from('inventory').insert(invRows);
        if (ie) throw ie;
      }

      setStatus('done');
    } catch (err) {
      setErrorMsg('Fejl: ' + (err.message || JSON.stringify(err)));
      setStatus('error');
    }
  };

  const totalBarLines = preview?.bars.reduce((s, b) => s + b.products.length, 0) ?? 0;
  const allUniqueProducts = preview
    ? [...new Set([...(preview.catalogs || []), ...(preview.bars || [])].flatMap(s => s.products.map(p => p.name)))]
    : [];

  const SheetPreview = ({ sheet }) => (
    <details style={{borderBottom:'1px solid var(--border)'}}>
      <summary style={{padding:'10px 14px', cursor:'pointer', fontWeight:500, fontSize:13, display:'flex', alignItems:'center', gap:8}}>
        {sheet.name}
        <span className="pill" style={{marginLeft:4, fontWeight:400}}>{sheet.products.length} varer</span>
        {sheet.type === 'catalog' && <span className="pill" style={{background:'var(--accent-subtle)', color:'var(--accent)', fontWeight:400}}>Katalog</span>}
      </summary>
      <table className="tbl" style={{margin:0}}>
        <thead><tr><th>Vare</th><th>Antal</th><th>Leverandør</th><th className="num">Pris</th></tr></thead>
        <tbody>
          {sheet.products.slice(0, 6).map((p, j) => (
            <tr key={j}>
              <td style={{fontWeight:500}}>{p.name}</td>
              <td className="muted">{sheet.type === 'catalog' ? '—' : p.qty}</td>
              <td className="muted">{p.supplier || '—'}</td>
              <td className="num">{p.price ? fmtKr(p.price) : '—'}</td>
            </tr>
          ))}
          {sheet.products.length > 6 && (
            <tr><td colSpan={4} style={{color:'var(--text-muted)', fontSize:12, padding:'6px 12px'}}>+{sheet.products.length - 6} flere...</td></tr>
          )}
        </tbody>
      </table>
    </details>
  );

  return (
    <div className="card card-pad" style={{maxWidth:680}}>
      <h3 className="card-title" style={{marginBottom:16}}>Importer startbeholdning fra Excel</h3>
      {status === 'idle' && (
        <div className="col" style={{gap:12}}>
          <p style={{fontSize:13, color:"var(--text-muted)", lineHeight:1.6}}>
            Upload et Excel-ark (.xlsx) med faner for barer og/eller sortiment. Første række tolkes som kolonneoverskrifter.
            Ark med navn som "Sortiment", "Produkter" eller "Leverandører" importeres som produktkatalog uden bar-tilknytning.
            Alle andre ark tolkes som barer.
          </p>
          <input type="file" accept=".xlsx,.xls" className="input"
                 style={{cursor:'pointer'}} onChange={handleFile}/>
        </div>
      )}
      {status === 'preview' && preview && (
        <div className="col" style={{gap:16}}>
          <div style={{display:'flex', gap:12, flexWrap:'wrap'}}>
            {preview.bars.length > 0 && <span className="pill">{preview.bars.length} barer</span>}
            {preview.catalogs.length > 0 && <span className="pill">{preview.catalogs.length} katalog-ark</span>}
            <span className="pill">{allUniqueProducts.length} unikke produkter</span>
            {totalBarLines > 0 && <span className="pill">{totalBarLines} beholdningslinjer</span>}
          </div>
          <div style={{border:'1px solid var(--border)', borderRadius:'var(--radius)', overflow:'hidden'}}>
            {preview.catalogs.length > 0 && (
              <div style={{padding:'8px 14px', fontSize:11, fontWeight:600, letterSpacing:'0.06em', textTransform:'uppercase', color:'var(--text-muted)', background:'var(--bg-sunken)', borderBottom:'1px solid var(--border)'}}>
                Katalog-ark (ingen bar-tilknytning)
              </div>
            )}
            {preview.catalogs.map((sheet, i) => <SheetPreview key={'c'+i} sheet={sheet}/>)}
            {preview.bars.length > 0 && preview.catalogs.length > 0 && (
              <div style={{padding:'8px 14px', fontSize:11, fontWeight:600, letterSpacing:'0.06em', textTransform:'uppercase', color:'var(--text-muted)', background:'var(--bg-sunken)', borderBottom:'1px solid var(--border)'}}>
                Bar-ark
              </div>
            )}
            {preview.bars.map((sheet, i) => <SheetPreview key={'b'+i} sheet={sheet}/>)}
          </div>
          <p style={{fontSize:12, color:"var(--warn)", lineHeight:1.5}}>
            Dette overskriver al eksisterende bar-, produkt- og beholdningsdata for organisationen.
          </p>
          <div style={{display:'flex', gap:8}}>
            <button className="btn" data-variant="primary" onClick={handleSave}>Gem til systemet</button>
            <button className="btn" data-variant="ghost" onClick={() => { setStatus('idle'); setPreview(null); }}>Annuller</button>
          </div>
        </div>
      )}
      {status === 'saving' && (
        <p style={{fontSize:13, color:'var(--text-muted)'}}>Gemmer data...</p>
      )}
      {status === 'done' && (
        <div className="col" style={{gap:12}}>
          <p style={{fontSize:13, color:'var(--ok)'}}>Import gennemført. Genindlæs siden for at se de nye data.</p>
          <button className="btn" data-variant="primary" onClick={() => window.location.reload()}>Genindlæs siden</button>
        </div>
      )}
      {status === 'error' && (
        <div className="col" style={{gap:12}}>
          <p style={{fontSize:13, color:'var(--danger)'}}>{errorMsg}</p>
          <button className="btn" data-variant="ghost" onClick={() => { setStatus('idle'); setErrorMsg(''); }}>Prøv igen</button>
        </div>
      )}
    </div>
  );
}

function SettingsScreen({ profile }) {
  const [tab, setTab] = useState("bars");
  const [staffList, setStaffList] = useState(() => D.staff);
  const [adding, setAdding] = useState(false);
  const [newName, setNewName] = useState("");
  const [newBar, setNewBar] = useState("");
  const [targets, setTargets] = useState(() =>
    Object.fromEntries(D.bars.map(b => [
      b.id,
      Object.fromEntries((D.stock[b.id] || []).map(r => [r.pid, r.target])),
    ]))
  );
  const [barList, setBarList] = useState(() => D.bars);
  const [editingBarId, setEditingBarId] = useState(null);
  const [editBarFields, setEditBarFields] = useState({ name: "", location: "", responsible: "" });
  const [targetBar, setTargetBar] = useState(D.bars[0].id);
  const [targetSaved, setTargetSaved] = useState(false);
  const [supplierList, setSupplierList] = useState(() => D.suppliers);
  const [editingSupId, setEditingSupId] = useState(null);
  const [editSupFields, setEditSupFields] = useState({ contact: "", email: "", phone: "", pdfParsing: false });
  const [addingSupplier, setAddingSupplier] = useState(false);
  const [newSupName, setNewSupName] = useState("");
  const [newSupEmail, setNewSupEmail] = useState("");
  const [newSupPhone, setNewSupPhone] = useState("");
  const [newSupContact, setNewSupContact] = useState("");
  const [productList, setProductList] = useState(() => D.products);
  const [editingProductId, setEditingProductId] = useState(null);
  const [editProductFields, setEditProductFields] = useState({ name: "", cat: "", unit: "", supplier: "", price: 0 });
  const [festivalFields, setFestivalFields] = useState({
    name: D.festival?.name ?? "Festegnen 2026",
    location: D.festival?.location ?? "Rødovre",
    startDate: D.festival?.startDate ?? "2026-05-08",
    endDate: D.festival?.endDate ?? "2026-05-09",
    orderDeadline: D.festival?.orderDeadline ?? "08:00",
    autoPdf: true,
    blockOnDiff: true,
  });
  const [festivalSaved, setFestivalSaved] = useState(false);

  const saveStaff = () => {
    if (!newName.trim()) return;
    setStaffList(l => [...l, { id: "s" + Date.now(), name: newName.trim(), barId: newBar || null }]);
    setNewName(""); setNewBar(""); setAdding(false);
  };

  return (
    <>
      <div className="page-header">
        <div>
          <h1 className="page-title">Indstillinger</h1>
          <p className="page-sub">Festival, barer, medarbejdere, varer og leverandører.</p>
        </div>
      </div>
      <div className="page-body">
        <div style={{display:"flex", gap:4, borderBottom:"1px solid var(--border)", marginBottom:18}}>
          {[
            ["bars",     "Barer",            D.bars.length],
            ["staff",    "Medarbejdere",     staffList.length],
            ["targets",  "Standardbeholdning", null],
            ["products", "Varer",            D.products.length],
            ["suppliers","Leverandører",     supplierList.length],
            ["festival", "Festival",         null],
            ["import",   "Importer",         null],
          ].map(([k, lbl, n]) => (
            <button key={k} className="btn" data-variant="ghost"
                    style={{
                      borderRadius:0, borderBottom: tab === k ? "2px solid var(--text)" : "2px solid transparent",
                      color: tab === k ? "var(--text)" : "var(--text-muted)", paddingBottom:8
                    }}
                    onClick={()=>setTab(k)}>
              {lbl} {n !== null && <span className="pill" style={{marginLeft:4}}>{n}</span>}
            </button>
          ))}
        </div>

        {tab === "bars" && (
          <div className="card" style={{overflow:"hidden"}}>
            <div className="card-head">
              <h3 className="card-title">Barer</h3>
              <button className="btn" data-size="sm" style={{marginLeft:"auto"}}><Ico.plus style={{width:13,height:13}}/> Ny bar</button>
            </div>
            <table className="tbl">
              <thead><tr><th>Navn</th><th>Placering</th><th>Ansvarlig</th><th>Status</th><th></th></tr></thead>
              <tbody>
                {barList.map(b => {
                  if (editingBarId === b.id) {
                    return (
                      <tr key={b.id}>
                        <td><input className="input" style={{width:"100%"}} value={editBarFields.name} onChange={e => setEditBarFields(f => ({ ...f, name: e.target.value }))} autoFocus/></td>
                        <td><input className="input" style={{width:"100%"}} value={editBarFields.location} onChange={e => setEditBarFields(f => ({ ...f, location: e.target.value }))}/></td>
                        <td><input className="input" style={{width:"100%"}} value={editBarFields.responsible} onChange={e => setEditBarFields(f => ({ ...f, responsible: e.target.value }))}/></td>
                        <td><Pill tone="ok" dot>Aktiv</Pill></td>
                        <td>
                          <div style={{display:"flex", gap:6}}>
                            <button className="btn" data-size="sm" data-variant="primary"
                                    onClick={() => { setBarList(l => l.map(x => x.id === b.id ? { ...x, ...editBarFields } : x)); setEditingBarId(null); }}>
                              Gem
                            </button>
                            <button className="btn" data-size="sm" data-variant="ghost" onClick={() => setEditingBarId(null)}>Annuller</button>
                          </div>
                        </td>
                      </tr>
                    );
                  }
                  return (
                    <tr key={b.id}>
                      <td style={{fontWeight:500}}>{b.name}</td>
                      <td className="muted">{b.location}</td>
                      <td className="muted">{b.responsible}</td>
                      <td><Pill tone="ok" dot>Aktiv</Pill></td>
                      <td className="col-w">
                        <button className="btn" data-size="sm" data-variant="ghost"
                                onClick={() => { setEditingBarId(b.id); setEditBarFields({ name: b.name, location: b.location, responsible: b.responsible }); }}>
                          Rediger
                        </button>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}

        {tab === "staff" && (
          <div className="card" style={{overflow:"hidden"}}>
            <div className="card-head">
              <h3 className="card-title">Medarbejdere</h3>
            </div>
            <table className="tbl">
              <thead>
                <tr><th>Navn</th><th>Bar-ansvarlig for</th><th></th></tr>
              </thead>
              <tbody>
                {staffList.map(s => (
                  <tr key={s.id}>
                    <td style={{fontWeight:500}}>{s.name}</td>
                    <td className="muted">{s.barId ? bar(s.barId)?.name : "—"}</td>
                    <td className="col-w">
                      <button className="btn" data-size="sm" data-variant="ghost"
                              onClick={() => setStaffList(l => l.filter(x => x.id !== s.id))}>
                        Fjern
                      </button>
                    </td>
                  </tr>
                ))}
                {adding && (
                  <tr>
                    <td>
                      <input className="input" placeholder="Navn" value={newName}
                             onChange={e => setNewName(e.target.value)}
                             onKeyDown={e => e.key === "Enter" && saveStaff()}
                             autoFocus style={{width:"100%"}}/>
                    </td>
                    <td>
                      <select className="input" value={newBar} onChange={e => setNewBar(e.target.value)} style={{width:"100%"}}>
                        <option value="">Ingen bar-ansvar</option>
                        {D.bars.map(b => <option key={b.id} value={b.id}>{b.name}</option>)}
                      </select>
                    </td>
                    <td>
                      <div style={{display:"flex", gap:6}}>
                        <button className="btn" data-size="sm" data-variant="primary" onClick={saveStaff}>Gem</button>
                        <button className="btn" data-size="sm" data-variant="ghost"
                                onClick={() => { setAdding(false); setNewName(""); setNewBar(""); }}>
                          Annuller
                        </button>
                      </div>
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
            {!adding && (
              <div style={{padding:"10px 16px", borderTop:"1px solid var(--border)"}}>
                <button className="btn" data-size="sm" onClick={() => setAdding(true)}>
                  <Ico.plus style={{width:13,height:13}}/> Tilføj medarbejder
                </button>
              </div>
            )}
          </div>
        )}

        {tab === "targets" && (
          <div>
            <div style={{display:"flex", gap:4, marginBottom:14, flexWrap:"wrap"}}>
              {D.bars.map(b => (
                <button key={b.id} className="btn" data-variant="ghost"
                        style={{borderRadius:0, borderBottom: targetBar === b.id ? "2px solid var(--text)" : "2px solid transparent", color: targetBar === b.id ? "var(--text)" : "var(--text-muted)", paddingBottom:8}}
                        onClick={() => { setTargetBar(b.id); setTargetSaved(false); }}>
                  {b.name}
                </button>
              ))}
            </div>
            <div className="card" style={{overflow:"hidden"}}>
              <div className="card-head">
                <h3 className="card-title">Standardbeholdning · {bar(targetBar)?.name}</h3>
                <span className="muted" style={{fontSize:12}}>Mål dag 2 = ønsket startbeholdning lørdag. Bestillingsforslag = mål minus aftenoptælling.</span>
              </div>
              <table className="tbl">
                <thead>
                  <tr>
                    <th>Vare</th>
                    <th>Kategori</th>
                    <th className="num">Min. grænse</th>
                    <th className="num" style={{width:160}}>Mål dag 2</th>
                  </tr>
                </thead>
                <tbody>
                  {(D.stock[targetBar] || []).map(row => {
                    const p = product(row.pid);
                    return (
                      <tr key={row.pid}>
                        <td style={{fontWeight:500}}>{p.name}</td>
                        <td className="muted">{p.cat}</td>
                        <td className="num muted">{row.par}</td>
                        <td>
                          <input
                            className="input"
                            type="number"
                            min="0"
                            style={{width:90, textAlign:"right"}}
                            value={targets[targetBar]?.[row.pid] ?? row.target}
                            onChange={e => {
                              const v = Math.max(0, parseInt(e.target.value) || 0);
                              setTargets(t => ({ ...t, [targetBar]: { ...t[targetBar], [row.pid]: v } }));
                              setTargetSaved(false);
                            }}
                          />
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
              <div style={{padding:"10px 16px", borderTop:"1px solid var(--border)", display:"flex", alignItems:"center", gap:12}}>
                <button className="btn" data-variant="primary"
                        onClick={() => setTargetSaved(true)}>
                  Gem standardbeholdning
                </button>
                {targetSaved && <span style={{fontSize:13, color:"var(--ok)"}}>Gemt</span>}
              </div>
            </div>
          </div>
        )}

        {tab === "products" && (
          <div className="card" style={{overflow:"hidden"}}>
            <div className="card-head">
              <h3 className="card-title">Varekatalog</h3>
              <button className="btn" data-size="sm" style={{marginLeft:"auto"}}><Ico.plus style={{width:13,height:13}}/> Ny vare</button>
            </div>
            <table className="tbl">
              <thead><tr><th>Navn</th><th>Kategori</th><th>Enhed</th><th>Leverandør</th><th className="num">Pris</th><th></th></tr></thead>
              <tbody>
                {productList.map(p => {
                  if (editingProductId === p.id) {
                    return (
                      <tr key={p.id}>
                        <td><input className="input" style={{width:"100%"}} value={editProductFields.name} onChange={e => setEditProductFields(f => ({ ...f, name: e.target.value }))} autoFocus/></td>
                        <td><input className="input" style={{width:"100%"}} value={editProductFields.cat} onChange={e => setEditProductFields(f => ({ ...f, cat: e.target.value }))}/></td>
                        <td><input className="input" style={{width:"100%"}} value={editProductFields.unit} onChange={e => setEditProductFields(f => ({ ...f, unit: e.target.value }))}/></td>
                        <td><input className="input" style={{width:"100%"}} value={editProductFields.supplier} onChange={e => setEditProductFields(f => ({ ...f, supplier: e.target.value }))}/></td>
                        <td><input className="input" type="number" style={{width:90, textAlign:"right"}} value={editProductFields.price} onChange={e => setEditProductFields(f => ({ ...f, price: Math.max(0, parseInt(e.target.value) || 0) }))}/></td>
                        <td>
                          <div style={{display:"flex", gap:6}}>
                            <button className="btn" data-size="sm" data-variant="primary"
                                    onClick={() => { setProductList(l => l.map(x => x.id === p.id ? { ...x, ...editProductFields } : x)); setEditingProductId(null); }}>
                              Gem
                            </button>
                            <button className="btn" data-size="sm" data-variant="ghost" onClick={() => setEditingProductId(null)}>Annuller</button>
                          </div>
                        </td>
                      </tr>
                    );
                  }
                  return (
                    <tr key={p.id}>
                      <td style={{fontWeight:500}}>{p.name}</td>
                      <td><Pill>{p.cat}</Pill></td>
                      <td className="muted">{p.unit}</td>
                      <td className="muted">{p.supplier}</td>
                      <td className="num">{fmtKr(p.price)}</td>
                      <td className="col-w">
                        <button className="btn" data-size="sm" data-variant="ghost"
                                onClick={() => { setEditingProductId(p.id); setEditProductFields({ name: p.name, cat: p.cat, unit: p.unit, supplier: p.supplier, price: p.price }); }}>
                          Rediger
                        </button>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}

        {tab === "suppliers" && (
          <div className="card" style={{overflow:"hidden"}}>
            <div className="card-head">
              <h3 className="card-title">Leverandører</h3>
              <button className="btn" data-size="sm" style={{marginLeft:"auto"}}
                      onClick={() => { setAddingSupplier(true); setEditingSupId(null); }}>
                <Ico.plus style={{width:13,height:13}}/> Ny leverandør
              </button>
            </div>
            <table className="tbl">
              <thead>
                <tr>
                  <th>Navn</th>
                  <th>Kontaktperson</th>
                  <th>E-mail</th>
                  <th>Telefon</th>
                  <th className="num">Varer</th>
                  <th>PDF-parsing</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                {supplierList.map(s => {
                  const count = D.products.filter(p => p.supplier === s.name).length;
                  if (editingSupId === s.id) {
                    return (
                      <tr key={s.id}>
                        <td style={{fontWeight:500}}>{s.name}</td>
                        <td><input className="input" style={{width:"100%"}} value={editSupFields.contact} onChange={e => setEditSupFields(f => ({ ...f, contact: e.target.value }))}/></td>
                        <td><input className="input" style={{width:"100%"}} type="email" value={editSupFields.email} onChange={e => setEditSupFields(f => ({ ...f, email: e.target.value }))}/></td>
                        <td><input className="input" style={{width:"100%"}} value={editSupFields.phone} onChange={e => setEditSupFields(f => ({ ...f, phone: e.target.value }))}/></td>
                        <td className="num">{count}</td>
                        <td>
                          <label style={{display:"flex", alignItems:"center", gap:6, fontSize:13, cursor:"pointer"}}>
                            <input type="checkbox" checked={editSupFields.pdfParsing} onChange={e => setEditSupFields(f => ({ ...f, pdfParsing: e.target.checked }))}/>
                            Aktiv
                          </label>
                        </td>
                        <td>
                          <div style={{display:"flex", gap:6}}>
                            <button className="btn" data-size="sm" data-variant="primary"
                                    onClick={() => { setSupplierList(l => l.map(x => x.id === s.id ? { ...x, ...editSupFields } : x)); setEditingSupId(null); }}>
                              Gem
                            </button>
                            <button className="btn" data-size="sm" data-variant="ghost" onClick={() => setEditingSupId(null)}>Annuller</button>
                          </div>
                        </td>
                      </tr>
                    );
                  }
                  return (
                    <tr key={s.id}>
                      <td style={{fontWeight:500}}>{s.name}</td>
                      <td className="muted">{s.contact}</td>
                      <td className="muted" style={{fontFamily:"var(--mono)", fontSize:12}}>{s.email}</td>
                      <td className="muted">{s.phone}</td>
                      <td className="num">{count}</td>
                      <td><Pill tone={s.pdfParsing ? "ok" : "info"} dot>{s.pdfParsing ? "Aktiv" : "Manuel"}</Pill></td>
                      <td className="col-w">
                        <button className="btn" data-size="sm" data-variant="ghost"
                                onClick={() => { setEditingSupId(s.id); setEditSupFields({ contact: s.contact, email: s.email, phone: s.phone, pdfParsing: s.pdfParsing }); setAddingSupplier(false); }}>
                          Rediger
                        </button>
                      </td>
                    </tr>
                  );
                })}
                {addingSupplier && (
                  <tr>
                    <td><input className="input" placeholder="Leverandørnavn" value={newSupName} onChange={e => setNewSupName(e.target.value)} style={{width:"100%"}} autoFocus/></td>
                    <td><input className="input" placeholder="Kontaktperson" value={newSupContact} onChange={e => setNewSupContact(e.target.value)} style={{width:"100%"}}/></td>
                    <td><input className="input" placeholder="E-mail" type="email" value={newSupEmail} onChange={e => setNewSupEmail(e.target.value)} style={{width:"100%"}}/></td>
                    <td><input className="input" placeholder="Telefon" value={newSupPhone} onChange={e => setNewSupPhone(e.target.value)} style={{width:"100%"}}/></td>
                    <td></td>
                    <td></td>
                    <td>
                      <div style={{display:"flex", gap:6}}>
                        <button className="btn" data-size="sm" data-variant="primary"
                                onClick={() => {
                                  if (!newSupName.trim()) return;
                                  setSupplierList(l => [...l, { id: "sup-" + Date.now(), name: newSupName.trim(), email: newSupEmail.trim(), phone: newSupPhone.trim(), contact: newSupContact.trim(), pdfParsing: false }]);
                                  setNewSupName(""); setNewSupEmail(""); setNewSupPhone(""); setNewSupContact(""); setAddingSupplier(false);
                                }}>
                          Gem
                        </button>
                        <button className="btn" data-size="sm" data-variant="ghost"
                                onClick={() => { setAddingSupplier(false); setNewSupName(""); setNewSupEmail(""); setNewSupPhone(""); setNewSupContact(""); }}>
                          Annuller
                        </button>
                      </div>
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        )}

        {tab === "import" && <ImportSection profile={profile}/>}

        {tab === "festival" && (
          <div className="card card-pad" style={{maxWidth:560}}>
            <div className="col" style={{gap:16}}>
              <Field label="Navn"><input className="input" value={festivalFields.name} onChange={e => { setFestivalFields(f => ({ ...f, name: e.target.value })); setFestivalSaved(false); }}/></Field>
              <Field label="Placering"><input className="input" value={festivalFields.location} onChange={e => { setFestivalFields(f => ({ ...f, location: e.target.value })); setFestivalSaved(false); }}/></Field>
              <div style={{display:"grid", gridTemplateColumns:"1fr 1fr", gap:12}}>
                <Field label="Startdato"><input className="input" type="date" value={festivalFields.startDate} onChange={e => { setFestivalFields(f => ({ ...f, startDate: e.target.value })); setFestivalSaved(false); }}/></Field>
                <Field label="Slutdato"><input className="input" type="date" value={festivalFields.endDate} onChange={e => { setFestivalFields(f => ({ ...f, endDate: e.target.value })); setFestivalSaved(false); }}/></Field>
              </div>
              <Field label="Standard bestillings-deadline"><input className="input" type="time" value={festivalFields.orderDeadline} onChange={e => { setFestivalFields(f => ({ ...f, orderDeadline: e.target.value })); setFestivalSaved(false); }}/></Field>
              <Field label="Krydstjek af kreditnotaer">
                <label style={{display:"flex", gap:8, alignItems:"center", fontSize:13}}>
                  <input type="checkbox" checked={festivalFields.autoPdf} onChange={e => { setFestivalFields(f => ({ ...f, autoPdf: e.target.checked })); setFestivalSaved(false); }}/> Læs PDF automatisk ved upload
                </label>
                <label style={{display:"flex", gap:8, alignItems:"center", fontSize:13, marginTop:6}}>
                  <input type="checkbox" checked={festivalFields.blockOnDiff} onChange={e => { setFestivalFields(f => ({ ...f, blockOnDiff: e.target.checked })); setFestivalSaved(false); }}/> Bloker bogføring ved afvigelser over 50 kr
                </label>
              </Field>
              <div style={{display:"flex", alignItems:"center", gap:12}}>
                <button className="btn" data-variant="primary" onClick={() => setFestivalSaved(true)}>Gem festival-indstillinger</button>
                {festivalSaved && <span style={{fontSize:13, color:"var(--ok)"}}>Gemt</span>}
              </div>
            </div>
          </div>
        )}
      </div>
    </>
  );
}

const Field = ({ label, children }) => (
  <label style={{display:"flex", flexDirection:"column", gap:5, fontSize:13}}>
    <span style={{fontSize:11.5, textTransform:"uppercase", letterSpacing:"0.04em", color:"var(--text-muted)", fontWeight:500}}>{label}</span>
    {children}
  </label>
);

const Stat = ({ label, value, delta, tone }) => (
  <div className={"stat " + (tone || "")}>
    <div className="stat-label">{label}</div>
    <div className="stat-value">{value}</div>
    {delta && <div className={"stat-delta " + (tone || "")}>{delta}</div>}
  </div>
);

window.LagerScreens3 = { CreditNotesScreen, DiscrepanciesScreen, SettingsScreen };
