// Jóváhagyó (Approver) nézet

const ApproverHome = ({ user, setView, openApproval, openPayout }) => {
  const pending = window.WORK_LOGS.filter(l => l.status === 'pending');
  const totalPending = window.totalPending();
  const totalApproved = window.totalSpent();
  const totalPaid = window.totalPaid();
  const totalDebt = totalApproved - totalPaid;

  return (
    <div className="main fade-in">
      <div>
        <div className="eyebrow">Jóváhagyó · {user.name}</div>
        <h2 style={{ marginTop: 4, textWrap: 'balance' }}>{pending.length > 0 ? `${pending.length} jóváhagyásra vár` : 'Minden naprakész'}</h2>
      </div>

      {/* Összegek */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
        <StatCard label="Várakozik" value={window.formatHufShort(totalPending) + ' Ft'} accent="warn" sub={pending.length + ' tétel'}/>
        <StatCard label="Kifizetésre vár" value={window.formatHufShort(totalDebt) + ' Ft'} accent="ink" sub="vállalkozóknak"/>
      </div>

      {/* Jóváhagyásra váró */}
      {pending.length > 0 && (
        <div className="stack-2">
          <div className="row between">
            <h3 style={{ whiteSpace: 'nowrap' }}>Jóváhagyásra vár</h3>
            <button className="btn ghost sm" onClick={() => setView('inbox')}>Mind <Icon name="chevron-r" size={14}/></button>
          </div>
          {pending.slice(0, 3).map(l => <ApprovalCard key={l.id} log={l} onClick={() => openApproval(l)}/>)}
        </div>
      )}

      {/* Vállalkozói egyenlegek */}
      <div className="stack-2">
        <div className="row between">
          <h3 style={{ whiteSpace: 'nowrap' }}>Egyenlegek</h3>
          <button className="btn ghost sm" onClick={() => setView('payouts')}>Mind <Icon name="chevron-r" size={14}/></button>
        </div>
        {window.getContractors().slice(0, 3).map(c => {
          const b = window.contractorBalance(c.id);
          if (b.balance <= 0) return null;
          return <ContractorBalanceCard key={c.id} contractor={c} balance={b} onClick={() => openPayout(c)}/>;
        })}
      </div>
    </div>
  );
};

const StatCard = ({ label, value, sub, accent = 'ink' }) => {
  const colors = { ink: 'var(--ink)', warn: '#8A6200', ok: 'var(--ok)', danger: 'var(--danger)' };
  return (
    <div className="card" style={{ padding: 12 }}>
      <div className="eyebrow" style={{ fontSize: 10 }}>{label}</div>
      <div className="num" style={{ fontSize: 22, fontWeight: 600, marginTop: 4, color: colors[accent], letterSpacing: '-0.01em' }}>{value}</div>
      {sub && <div className="muted" style={{ fontSize: 11, marginTop: 2 }}>{sub}</div>}
    </div>
  );
};

const ApprovalCard = ({ log, onClick }) => {
  const c = window.getUser(log.contractorId);
  const phase = window.getPhase(log.phaseId);
  const task = window.getParentTask(log.parentTaskId);
  const { total } = window.computeWorkLog(log);
  const taskBudget = task.budget;
  const taskSpent = window.parentTaskSpent(log.parentTaskId);
  const remaining = taskBudget - taskSpent;
  const overrun = total > remaining;

  return (
    <div className="card tap" onClick={onClick} style={{ padding: 12, display: 'flex', gap: 12 }}>
      <div className="phase-stripe" style={{ background: phase?.color }}/>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="row between" style={{ gap: 8, alignItems: 'flex-start' }}>
          <div className="row" style={{ gap: 8, minWidth: 0, flex: 1 }}>
            <Avatar user={c} size="sm"/>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontWeight: 500, fontSize: 13, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{c.name}</div>
              <div className="muted mono" style={{ fontSize: 10, whiteSpace: 'nowrap' }}>{window.formatDateShort(log.date)} · {phase?.code}</div>
            </div>
          </div>
          <div className="num" style={{ fontWeight: 600, fontSize: 15, whiteSpace: 'nowrap', flexShrink: 0 }}>{window.formatHufShort(total)} Ft</div>
        </div>

        <div style={{ marginTop: 8, fontSize: 13, fontWeight: 500, lineHeight: 1.3 }}>{task.name}</div>
        <div className="muted" style={{ fontSize: 12, marginTop: 2, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>
          {log.description}
        </div>

        <div className="row between" style={{ marginTop: 10, fontSize: 11 }}>
          <div className="muted">
            {(() => {
              const s = window.workLogStats(log);
              if (s.isPurchase || !s.hasLabor) return <span className="num">Beszerzés</span>;
              return <span className="num">{s.totalWorkers}fő × {s.totalHours}ó</span>;
            })()}
            {log.materialCost > 0 && <> · anyag <span className="num">{window.formatHufShort(log.materialCost)}</span></>}
            {(() => {
              const list = Array.isArray(log.photoList) ? log.photoList : (Array.isArray(log.photos) ? log.photos : null);
              const n = list ? list.length : (typeof log.photos === 'number' ? log.photos : 0);
              return n > 0 ? <> · <Icon name="camera" size={11}/> {n}</> : null;
            })()}
          </div>
          <div className={overrun ? 'mono' : 'mono muted'} style={{ fontSize: 11, color: overrun ? 'var(--danger)' : undefined, fontWeight: overrun ? 600 : undefined, whiteSpace: 'nowrap' }}>
            {overrun ? '!' : ''} keret: {window.formatHufShort(remaining)}
          </div>
        </div>
      </div>
    </div>
  );
};

const ContractorBalanceCard = ({ contractor, balance, onClick }) => (
  <div className="card tap" onClick={onClick} style={{ padding: 12, display: 'flex', alignItems: 'center', gap: 12 }}>
    <Avatar user={contractor}/>
    <div style={{ flex: 1, minWidth: 0 }}>
      <div className="row between">
        <div>
          <div style={{ fontWeight: 500, fontSize: 14 }}>{contractor.name}</div>
          <div className="muted" style={{ fontSize: 11 }}>{contractor.skill}</div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div className="num" style={{ fontWeight: 600, whiteSpace: 'nowrap' }}>{window.formatHufShort(balance.balance)} Ft</div>
          <div className="muted" style={{ fontSize: 10, whiteSpace: 'nowrap' }}>kifizetésre vár</div>
        </div>
      </div>
    </div>
    <Icon name="chevron-r" size={18}/>
  </div>
);

const ApproverInbox = ({ openApproval }) => {
  const [filter, setFilter] = React.useState('pending');
  const all = window.WORK_LOGS.slice().reverse();
  const filtered = filter === 'all' ? all : all.filter(l => l.status === filter);
  const counts = {
    all: all.length,
    pending: all.filter(l => l.status === 'pending').length,
    approved: all.filter(l => l.status === 'approved').length,
    rejected: all.filter(l => l.status === 'rejected').length,
  };
  return (
    <div className="main fade-in">
      <h2>Bejövő teljesítések</h2>
      <div className="tabs">
        {[
          { k: 'pending', l: 'Várakozik' },
          { k: 'approved', l: 'Jóváhagyva' },
          { k: 'rejected', l: 'Elutasítva' },
          { k: 'all', l: 'Mind' },
        ].map(t => (
          <button key={t.k} className={filter === t.k ? 'active' : ''} onClick={() => setFilter(t.k)}>
            {t.l} <span className="muted" style={{ fontWeight: 400 }}>{counts[t.k]}</span>
          </button>
        ))}
      </div>
      <div className="stack-2">
        {filtered.map(l => <ApprovalCard key={l.id} log={l} onClick={() => openApproval(l)}/>)}
        {filtered.length === 0 && <div className="muted" style={{ padding: 30, textAlign: 'center' }}>Nincs ilyen tétel.</div>}
      </div>
    </div>
  );
};

// Részletes jóváhagyási nézet
const ApprovalDetail = ({ log, onClose, onDecide }) => {
  const c = window.getUser(log.contractorId);
  const phase = window.getPhase(log.phaseId);
  const task = window.getParentTask(log.parentTaskId);
  const { labor, total } = window.computeWorkLog(log);
  const taskBudget = task.budget;
  const taskSpent = window.parentTaskSpent(log.parentTaskId);
  const remaining = taskBudget - taskSpent - (log.status === 'pending' ? 0 : 0);
  const [approvedAmount, setApprovedAmount] = React.useState(total);
  const [note, setNote] = React.useState('');
  const [showReject, setShowReject] = React.useState(false);

  return (
    <div style={{ position: 'fixed', inset: 0, background: 'var(--bg)', zIndex: 60, overflowY: 'auto' }} className="fade-in">
      <div className="topbar" style={{ position: 'sticky', top: 0 }}>
        <button className="btn ghost sm" onClick={onClose} style={{ padding: 8 }}><Icon name="arrow-l" size={20}/></button>
        <h1>Teljesítés #{String(log.id).padStart(4, '0')}</h1>
        <div className="right"><StatusPill status={log.status}/></div>
      </div>

      <div className="main" style={{ paddingBottom: 140 }}>
        {/* Kontaktor + dátum */}
        <div className="card" style={{ padding: 14, display: 'flex', alignItems: 'center', gap: 12 }}>
          <Avatar user={c} size="lg"/>
          <div>
            <div style={{ fontWeight: 600 }}>{c.name}</div>
            <div className="muted" style={{ fontSize: 12 }}>{c.skill} · {window.formatHuf(c.hourlyRate)}/óra</div>
            <div className="muted mono" style={{ fontSize: 11, marginTop: 4 }}>
              <Icon name="calendar" size={11}/> {window.formatDate(log.date)}
            </div>
          </div>
        </div>

        {/* Mit */}
        <div className="card stack-2">
          <PhaseChip phaseId={log.phaseId}/>
          <div style={{ fontWeight: 600, fontSize: 17, lineHeight: 1.3 }}>{task.name}</div>
          <div style={{ fontSize: 14, lineHeight: 1.5, color: 'var(--ink-2)' }}>{log.description}</div>
        </div>

        {/* Számítás */}
        <div className="card stack-2">
          <div className="eyebrow">Számítás</div>
          {(() => {
            const s = window.workLogStats(log);
            if (s.hasLabor) {
              return <CalcRow label={`Munkadíj (${s.totalWorkers} fő × ${s.totalHours / Math.max(1, s.totalWorkers)} óra × ${window.formatHufShort(log.hourlyRate)} Ft)`} value={labor}/>;
            }
            return null;
          })()}
          {log.materialCost > 0 && <CalcRow label="Anyagköltség" value={log.materialCost}/>}
          <div className="divider"/>
          <CalcRow label="Összesen" value={total} bold/>
        </div>

        {/* Költségvetés állapot */}
        <div className="card stack-2">
          <div className="eyebrow">Főfeladat költségvetése</div>
          <CalcRow label="Teljes keret" value={taskBudget} muted/>
          <CalcRow label="Eddig jóváhagyva" value={taskSpent} muted/>
          <div className="divider"/>
          <CalcRow label="Maradék (jelen tétel előtt)" value={remaining} bold color={remaining > 0 ? 'var(--ok)' : 'var(--danger)'}/>
          <BudgetBar spent={taskSpent} pending={total} budget={taskBudget} height={10}/>
          {total > remaining && (
            <div style={{ padding: 10, background: 'var(--danger-l)', color: 'var(--danger)', borderRadius: 8, fontSize: 13, marginTop: 6 }}>
              ⚠ A tétel <b>{window.formatHuf(total - remaining)}</b>-tal túllépi a fennmaradó keretet.
            </div>
          )}
        </div>

        {/* Fotók */}
        {(() => {
          const photoArr = Array.isArray(log.photoList) ? log.photoList
            : (Array.isArray(log.photos) ? log.photos : []);
          const photoCount = photoArr.length || (typeof log.photos === 'number' ? log.photos : 0);
          return (
            <div className="stack-2">
              <div className="eyebrow">Fotók ({photoCount})</div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 6 }}>
                {photoArr.length > 0
                  ? photoArr.map(p => (
                    <a key={p.id} href={p.url} target="_blank" rel="noreferrer" className="photo-ph"
                       style={{ aspectRatio: '1', overflow: 'hidden', borderColor: 'transparent', padding: 0 }}>
                      <img src={p.url} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }}/>
                    </a>
                  ))
                  : Array.from({ length: photoCount }).map((_, i) => (
                    <div key={i} className="photo-ph" style={{ aspectRatio: '1', background: 'var(--ink-4)', color: 'white', borderColor: 'transparent' }}>
                      <Icon name="image" size={20}/>
                    </div>
                  ))}
                {photoCount === 0 && <div className="muted" style={{ fontSize: 13 }}>Nincs feltöltött fotó.</div>}
              </div>
            </div>
          );
        })()}

        {log.status === 'pending' && (
          <>
            <div className="field">
              <label className="label">Jóváhagyott összeg</label>
              <div className="row" style={{ gap: 8 }}>
                <input type="number" className="input num" value={approvedAmount} onChange={e => setApprovedAmount(parseInt(e.target.value) || 0)}/>
                <span className="mono muted">Ft</span>
              </div>
              <div className="muted" style={{ fontSize: 11, marginTop: 4 }}>Lehet kevesebb, mint a kért összeg.</div>
            </div>
            <div className="field">
              <label className="label">Megjegyzés (opcionális)</label>
              <textarea className="textarea" value={note} onChange={e => setNote(e.target.value)} placeholder="Pl. Köszi, holnap kifizetem."/>
            </div>
          </>
        )}
      </div>

      {/* CTA */}
      {log.status === 'pending' && (
        <div className="sticky-cta" style={{ borderTop: '1px solid var(--line)', background: 'var(--bg)' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 2fr', gap: 8 }}>
            <button className="btn full" onClick={() => setShowReject(true)} style={{ borderColor: 'var(--danger)', color: 'var(--danger)' }}>
              <Icon name="x" size={18}/> Elutasít
            </button>
            <button className="btn ok full lg" onClick={() => onDecide('approved', approvedAmount, note)}>
              <Icon name="check" size={18} stroke={2.4}/> Jóváhagy {window.formatHufShort(approvedAmount)} Ft
            </button>
          </div>
        </div>
      )}

      {showReject && (
        <Sheet open onClose={() => setShowReject(false)} title="Elutasítás indoka">
          <textarea className="textarea" value={note} onChange={e => setNote(e.target.value)} placeholder="Pl. Hiányos leírás, kérlek pontosítsd." rows={4}/>
          <div className="row" style={{ gap: 8, marginTop: 12 }}>
            <button className="btn full" onClick={() => setShowReject(false)}>Mégse</button>
            <button className="btn danger full" onClick={() => { onDecide('rejected', 0, note); setShowReject(false); }}>Elutasít</button>
          </div>
        </Sheet>
      )}
    </div>
  );
};

const CalcRow = ({ label, value, bold, muted, color }) => (
  <div className="row between" style={{ fontSize: bold ? 16 : 13 }}>
    <span className="muted" style={{ color: muted ? 'var(--ink-3)' : (bold ? 'var(--ink)' : 'var(--ink-2)'), fontSize: bold ? 14 : 13 }}>{label}</span>
    <span className="num" style={{ fontWeight: bold ? 700 : 500, color: color }}>{window.formatHuf(value)}</span>
  </div>
);

// === Kifizetés képernyő ===
const Payouts = ({ openPayout, openInvoiceScan }) => {
  const contractors = window.getContractors();
  return (
    <div className="main fade-in">
      <div className="row between">
        <h2>Kifizetések</h2>
        <button className="btn sm accent" onClick={openInvoiceScan}>
          <Icon name="camera" size={14}/> Számla
        </button>
      </div>

      <div className="stack-2">
        <div className="eyebrow">Vállalkozók</div>
        {contractors.map(c => {
          const b = window.contractorBalance(c.id);
          return <ContractorBalanceCard key={c.id} contractor={c} balance={b} onClick={() => openPayout(c)}/>;
        })}
      </div>

      <div className="stack-2">
        <div className="eyebrow">Legutóbbi kifizetések</div>
        {window.PAYMENTS.slice().reverse().map(p => {
          const c = window.getUser(p.contractorId);
          return (
            <div key={p.id} className="card" style={{ padding: 12, display: 'flex', alignItems: 'center', gap: 10 }}>
              <Avatar user={c} size="sm"/>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 500, fontSize: 13 }}>{c.name}</div>
                <div className="muted mono" style={{ fontSize: 11 }}>{window.formatDate(p.paidAt)}</div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div className="num" style={{ fontWeight: 600 }}>{window.formatHuf(p.amountHuf)}</div>
                {p.currency !== 'HUF' && <div className="muted mono" style={{ fontSize: 11 }}>{p.originalAmount} {p.currency} @ {p.fxRate}</div>}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

// Kifizetés végrehajtás
const PayoutSheet = ({ contractor, onClose, onSubmit }) => {
  const balance = window.contractorBalance(contractor.id);
  const [currency, setCurrency] = React.useState('HUF');
  const [amount, setAmount] = React.useState(balance.balance);
  const [note, setNote] = React.useState('');
  const [invoicePhoto, setInvoicePhoto] = React.useState(null);
  const invoiceRef = React.useRef(null);
  const fx = window.FX_RATES[currency];
  const amountInHuf = currency === 'HUF' ? amount : Math.round(amount * fx);
  const remaining = balance.balance - amountInHuf;

  return (
    <Sheet open onClose={onClose} title={`Kifizetés — ${contractor.name}`}>
      <div className="card" style={{ padding: 12, marginBottom: 14, background: 'var(--surface-2)' }}>
        <CalcRow label="Jóváhagyva neki" value={balance.approved} muted/>
        <CalcRow label="Eddig kifizetve" value={balance.paid} muted/>
        <div className="divider"/>
        <CalcRow label="Aktuális tartozás" value={balance.balance} bold color="var(--accent-d)"/>
      </div>

      <div className="field">
        <label className="label">Pénznem</label>
        <div className="row" style={{ gap: 6 }}>
          {['HUF', 'EUR', 'USD'].map(cur => (
            <button key={cur} className={'chip ' + (currency === cur ? 'active' : '')} style={{ flex: 1, justifyContent: 'center', padding: 10 }} onClick={() => setCurrency(cur)}>{cur}</button>
          ))}
        </div>
      </div>

      <div className="field">
        <label className="label">Most kifizetendő ({currency})</label>
        <div className="row" style={{ gap: 8 }}>
          <input type="number" className="input num" value={amount} onChange={e => setAmount(parseFloat(e.target.value) || 0)}/>
          <span className="mono muted">{currency}</span>
        </div>
        {currency !== 'HUF' && (
          <div className="muted mono" style={{ fontSize: 11, marginTop: 6 }}>
            Mai MNB árfolyam: 1 {currency} = {fx} Ft → <b className="num">{window.formatHuf(amountInHuf)}</b>
          </div>
        )}
      </div>

      <div className="field">
        <label className="label">Megjegyzés</label>
        <input className="input" value={note} onChange={e => setNote(e.target.value)} placeholder="pl. anyagvásárlásra"/>
      </div>

      <div className="field">
        <label className="label">Számla fotó (opcionális)</label>
        <input ref={invoiceRef} type="file" accept="image/*,.pdf" style={{ display: 'none' }}
          onChange={e => setInvoicePhoto(e.target.files?.[0] || null)}/>
        <button className="btn ghost full" onClick={() => invoiceRef.current?.click()}>
          <Icon name="camera" size={16}/> {invoicePhoto ? invoicePhoto.name : 'Fotó / PDF feltöltése'}
        </button>
      </div>

      <div className="card" style={{ padding: 12, background: 'var(--ink)', color: 'var(--bg)', border: 'none', marginTop: 8 }}>
        <CalcRow label="Kifizetés HUF-ban" value={amountInHuf} bold color="var(--bg)"/>
        <div style={{ height: 6 }}/>
        <CalcRow label="Fennmaradó tartozás" value={remaining} muted color="rgba(255,255,255,0.7)"/>
      </div>

      <div className="row" style={{ gap: 8, marginTop: 14 }}>
        <button className="btn full" onClick={onClose}>Mégse</button>
        <button className="btn accent full" onClick={() => onSubmit({ contractorId: contractor.id, amountHuf: amountInHuf, originalAmount: amount, currency, fxRate: fx, note, invoicePhoto })}>
          <Icon name="wallet" size={16}/> Rögzítés
        </button>
      </div>
    </Sheet>
  );
};

// Számla scan / OCR mock
const InvoiceScan = ({ onClose, onSave }) => {
  const [step, setStep] = React.useState('camera');
  const [vendor, setVendor] = React.useState('');
  const [amount, setAmount] = React.useState(0);
  const [phaseId, setPhaseId] = React.useState(null);

  const fakeScan = () => {
    setStep('result');
    setVendor('PRAKTIKER Kft.');
    setAmount(187420);
    setPhaseId(9);
  };

  return (
    <Sheet open onClose={onClose} title="Számla rögzítése">
      {step === 'camera' && (
        <div className="stack-4">
          <div className="photo-ph" style={{ aspectRatio: '4/3', flexDirection: 'column', gap: 8, fontSize: 12 }}>
            <Icon name="camera" size={36}/>
            <span>Készíts fotót a számláról</span>
          </div>
          <button className="btn accent full lg" onClick={fakeScan}>
            <Icon name="flash" size={18}/> Beolvasás
          </button>
          <div className="muted" style={{ fontSize: 11, textAlign: 'center' }}>Az OCR automatikusan kitölti a mezőket — javíthatod.</div>
        </div>
      )}
      {step === 'result' && (
        <div className="stack-2">
          <div className="row" style={{ gap: 10, alignItems: 'center', padding: '8px 10px', background: 'var(--ok-l)', color: 'var(--ok)', borderRadius: 8, fontSize: 13 }}>
            <Icon name="check" size={16} stroke={2.4}/> OCR kész
          </div>
          <div className="field">
            <label className="label">Eladó</label>
            <input className="input" value={vendor} onChange={e => setVendor(e.target.value)}/>
          </div>
          <div className="field">
            <label className="label">Összeg (Ft)</label>
            <input type="number" className="input num" value={amount} onChange={e => setAmount(parseInt(e.target.value) || 0)}/>
          </div>
          <div className="field">
            <label className="label">Fázis</label>
            <select className="select" value={phaseId || ''} onChange={e => setPhaseId(parseInt(e.target.value))}>
              <option value="">Válassz…</option>
              {window.PHASES.map(p => <option key={p.id} value={p.id}>{p.code} — {p.name}</option>)}
            </select>
          </div>
          <div className="row" style={{ gap: 8, marginTop: 10 }}>
            <button className="btn full" onClick={onClose}>Mégse</button>
            <button className="btn accent full" onClick={() => { onSave({ vendor, amount, phaseId }); onClose(); }}>Rögzít</button>
          </div>
        </div>
      )}
    </Sheet>
  );
};

Object.assign(window, { ApproverHome, ApproverInbox, ApprovalDetail, Payouts, PayoutSheet, InvoiceScan, ApprovalCard, ContractorBalanceCard, StatCard, CalcRow });
