// Vállalkozó (Contractor) nézet — gyors teljesítés-rögzítés a fókusz

const ContractorHome = ({ user, setView, openLogger }) => {
  const myLogs = window.WORK_LOGS.filter(l => l.contractorId === user.id).slice().reverse();
  const balance = window.contractorBalance(user.id);
  const todayLogs = myLogs.filter(l => l.date === window.TODAY);

  return (
    <div className="main fade-in">
      {/* Üdvözlő blokk */}
      <div>
        <div className="eyebrow">Szia, {user.name.split(' ')[0]}</div>
        <h2 style={{ marginTop: 4 }}>Mit csináltál ma?</h2>
      </div>

      {/* Egyenleg kártya */}
      <div className="card glow">
        <div className="row between" style={{ alignItems: 'flex-start' }}>
          <div>
            <div className="eyebrow" style={{ color: 'var(--accent-d)' }}>Egyenleged</div>
            <div className="num" style={{ fontSize: 28, fontWeight: 600, marginTop: 4, letterSpacing: '-0.02em', whiteSpace: 'nowrap' }}>
              {window.formatHufShort(balance.balance)} <span style={{ fontSize: 18, fontWeight: 500, color: 'var(--ink-2)' }}>Ft</span>
            </div>
            <div className="muted" style={{ fontSize: 12, marginTop: 2 }}>kifizetésre vár</div>
          </div>
          <button className="btn sm" onClick={() => setView('history')}>
            <Icon name="list" size={14}/> Előzmények
          </button>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginTop: 14, paddingTop: 14, borderTop: '1px solid var(--line-2)' }}>
          <div>
            <div className="muted" style={{ fontSize: 11 }}>Jóváhagyva</div>
            <div className="num" style={{ fontWeight: 500 }}>{window.formatHuf(balance.approved)}</div>
          </div>
          <div>
            <div className="muted" style={{ fontSize: 11 }}>Kifizetve</div>
            <div className="num" style={{ fontWeight: 500 }}>{window.formatHuf(balance.paid)}</div>
          </div>
        </div>
      </div>

      {/* Új teljesítés CTA */}
      <button className="btn accent lg full" onClick={openLogger} style={{ padding: '20px 16px', fontSize: 17, gap: 12 }}>
        <Icon name="plus" size={22} stroke={2.4}/>
        Új teljesítés rögzítése
      </button>

      {/* Mai aktivitás */}
      {todayLogs.length > 0 ? (
        <div className="stack-2">
          <div className="row between">
            <h3>Mai munka</h3>
            <span className="muted" style={{ fontSize: 12 }}>{todayLogs.length} bejegyzés</span>
          </div>
          {todayLogs.map(l => <LogCard key={l.id} log={l} />)}
        </div>
      ) : (
        <Hint>
          Tipp: a leggyorsabb, ha rögtön a munka után rögzíted a teljesítést. 4 koppintás, 1 fotó, kész.
        </Hint>
      )}

      {/* Utolsó néhány teljesítés */}
      <div className="stack-2">
        <div className="row between">
          <h3>Legutóbbi teljesítések</h3>
          <button className="btn ghost sm" onClick={() => setView('history')}>Mind <Icon name="chevron-r" size={14}/></button>
        </div>
        {myLogs.slice(0, 4).map(l => <LogCard key={l.id} log={l} />)}
      </div>
    </div>
  );
};

const LogCard = ({ log, onClick }) => {
  const { labor, total } = window.computeWorkLog(log);
  const phase = window.getPhase(log.phaseId);
  const task = window.getParentTask(log.parentTaskId);
  return (
    <div className="card" style={{ padding: 12, display: 'flex', gap: 12 }} onClick={onClick}>
      <div className="phase-stripe" style={{ background: phase?.color }}/>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="row between">
          <div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>
            {window.formatDateShort(log.date)} · {phase?.code}
          </div>
          <StatusPill status={log.status}/>
        </div>
        <div style={{ fontWeight: 500, marginTop: 2, lineHeight: 1.3 }}>{task?.name}</div>
        <div className="muted" style={{ fontSize: 13, marginTop: 2, display: '-webkit-box', WebkitLineClamp: 1, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>
          {log.description}
        </div>
        <div className="row between" style={{ marginTop: 8 }}>
          <div className="row" style={{ gap: 6, fontSize: 11, color: 'var(--ink-3)' }}>
            {(() => {
              const stats = window.workLogStats(log);
              if (stats.isPurchase || !stats.hasLabor) {
                return <span><Icon name="receipt" size={12}/> Beszerzés</span>;
              }
              return (
                <>
                  <span><Icon name="users" size={12}/> {stats.totalWorkers} fő</span>
                  <span>·</span>
                  <span><Icon name="clock" size={12}/> {stats.totalHours} óra</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 ? <><span>·</span><span><Icon name="camera" size={12}/> {n}</span></> : null;
            })()}
          </div>
          <div className="num" style={{ fontWeight: 600, fontSize: 14 }}>{window.formatHufShort(total)} Ft</div>
        </div>
        {log.status === 'rejected' && log.rejectReason && (
          <div style={{ marginTop: 8, padding: 8, background: 'var(--danger-l)', color: 'var(--danger)', borderRadius: 8, fontSize: 12 }}>
            {log.rejectReason}
          </div>
        )}
      </div>
    </div>
  );
};

// === Új teljesítés flow ===
// Két típus: "Munka" (egy vagy több csapat × óra) vagy "Beszerzés" (csak anyag/számla).
const Logger = ({ user, onClose, onSubmit }) => {
  const [entryType, setEntryType] = React.useState('labor'); // 'labor' | 'purchase'
  const [phaseId, setPhaseId] = React.useState(null);
  const [taskId, setTaskId]   = React.useState(null);
  const [date, setDate]       = React.useState(window.TODAY);
  const [tiers, setTiers]     = React.useState([{ workers: 2, hours: 8 }]);
  const [materialCost, setMaterial] = React.useState(0);
  const [description, setDesc] = React.useState('');
  // photos: [{ id, file, previewUrl }]
  const [photos, setPhotos]    = React.useState([]);
  const photoInputRef = React.useRef(null);

  const updateTier = (i, patch) => setTiers(tiers.map((t, idx) => idx === i ? { ...t, ...patch } : t));
  const addTier = () => setTiers([...tiers, { workers: 1, hours: 8 }]);
  const removeTier = (i) => setTiers(tiers.filter((_, idx) => idx !== i));

  const onPhotoPick = (e) => {
    const files = Array.from(e.target.files || []);
    const next = files.map(f => ({
      id: Date.now() + Math.random(),
      file: f,
      previewUrl: f.type.startsWith('image/') ? URL.createObjectURL(f) : null,
    }));
    setPhotos(p => [...p, ...next]);
    e.target.value = '';
  };

  const labor = entryType === 'labor'
    ? tiers.reduce((s, t) => s + (t.workers || 0) * (t.hours || 0) * user.hourlyRate, 0)
    : 0;
  const total = labor + materialCost;
  const totalWorkers = tiers.reduce((s, t) => s + (t.workers || 0), 0);
  const totalHours = tiers.reduce((s, t) => s + (t.workers || 0) * (t.hours || 0), 0);

  const tasks = phaseId ? window.PARENT_TASKS.filter(t => t.phaseId === phaseId) : [];

  const taskBudget = taskId ? window.getParentTask(taskId).budget : 0;
  const taskSpent  = taskId ? window.parentTaskSpent(taskId) : 0;
  const taskPending = taskId ? window.parentTaskPending(taskId) : 0;
  const remaining = taskBudget - taskSpent - taskPending;

  const canSubmit = phaseId && taskId && date && description.trim().length > 0 && (
    totalHours > 0 || materialCost > 0
  );

  return (
    <div style={{ position: 'fixed', inset: 0, background: 'var(--bg)', zIndex: 60, display: 'flex', flexDirection: 'column', 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="x" size={20}/></button>
        <div>
          <h1>Új teljesítés</h1>
          <div className="sub mono" style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{user.name}</div>
        </div>
      </div>

      <div className="main" style={{ paddingBottom: 360, gap: 22 }}>

        {/* 1. Fázis */}
        <div className="stack-2">
          <div className="row between">
            <div className="eyebrow">1 · Fázis</div>
            {phaseId && <button className="btn ghost sm" onClick={() => { setPhaseId(null); setTaskId(null); }}>Csere</button>}
          </div>
          {!phaseId ? (
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
              {window.PHASES.map(p => (
                <button key={p.id} className="card tap" onClick={() => setPhaseId(p.id)}
                  style={{ padding: 12, textAlign: 'left', display: 'flex', flexDirection: 'column', gap: 6, border: '1px solid var(--line)', background: 'var(--surface)' }}>
                  <div className="row" style={{ gap: 8 }}>
                    <span className="mono" style={{ background: p.color, color: 'white', padding: '2px 6px', borderRadius: 4, fontSize: 10, fontWeight: 600 }}>{p.code}</span>
                  </div>
                  <div style={{ fontSize: 13, fontWeight: 500, lineHeight: 1.25 }}>{p.name}</div>
                </button>
              ))}
            </div>
          ) : (
            <div className="card" style={{ padding: 12, display: 'flex', alignItems: 'center', gap: 10, background: 'var(--surface-2)' }}>
              <span className="mono" style={{ background: window.getPhase(phaseId).color, color: 'white', padding: '4px 8px', borderRadius: 4, fontSize: 11, fontWeight: 600 }}>
                {window.getPhase(phaseId).code}
              </span>
              <span style={{ fontWeight: 500 }}>{window.getPhase(phaseId).name}</span>
            </div>
          )}
        </div>

        {/* 2. Főfeladat */}
        {phaseId && (
          <div className="stack-2">
            <div className="row between">
              <div className="eyebrow">2 · Főfeladat</div>
              {taskId && <button className="btn ghost sm" onClick={() => setTaskId(null)}>Csere</button>}
            </div>
            {!taskId ? (
              <div className="stack-2">
                {tasks.map(t => {
                  const sp = window.parentTaskSpent(t.id);
                  const pct = t.budget > 0 ? (sp / t.budget) * 100 : 0;
                  return (
                    <button key={t.id} className="card tap" onClick={() => setTaskId(t.id)}
                      style={{ padding: 12, textAlign: 'left', display: 'flex', flexDirection: 'column', gap: 8 }}>
                      <div className="row between">
                        <span style={{ fontWeight: 500, lineHeight: 1.3 }}>{t.name}</span>
                        <span className="num muted" style={{ fontSize: 12 }}>{window.formatHufShort(t.budget)}</span>
                      </div>
                      <BudgetBar spent={sp} budget={t.budget} height={4}/>
                    </button>
                  );
                })}
              </div>
            ) : (
              <div className="card" style={{ padding: 12, background: 'var(--surface-2)' }}>
                <div style={{ fontWeight: 500 }}>{window.getParentTask(taskId).name}</div>
                <div className="row between" style={{ marginTop: 8, fontSize: 12, gap: 8 }}>
                  <span className="muted" style={{ whiteSpace: 'nowrap' }}>Keret</span>
                  <span className="num" style={{ whiteSpace: 'nowrap' }}>{window.formatHuf(taskBudget)}</span>
                </div>
                <div className="row between" style={{ fontSize: 12, gap: 8 }}>
                  <span className="muted" style={{ whiteSpace: 'nowrap' }}>Felhasznált</span>
                  <span className="num" style={{ whiteSpace: 'nowrap' }}>{window.formatHuf(taskSpent)}</span>
                </div>
                <div className="row between" style={{ fontSize: 12, fontWeight: 600, paddingTop: 6, marginTop: 6, borderTop: '1px solid var(--line-2)', gap: 8 }}>
                  <span style={{ whiteSpace: 'nowrap' }}>Maradvány</span>
                  <span className="num" style={{ color: remaining > 0 ? 'var(--ok)' : 'var(--danger)', whiteSpace: 'nowrap' }}>{window.formatHuf(remaining)}</span>
                </div>
              </div>
            )}
          </div>
        )}

        {/* 3. Munka + anyag VAGY csak beszerzés */}
        {taskId && (
          <div className="stack-2">
            <div className="eyebrow">3 · Mit rögzítesz?</div>

            {/* Típusváltó */}
            <div className="tabs">
              <button className={entryType === 'labor' ? 'active' : ''} onClick={() => setEntryType('labor')}>
                <Icon name="users" size={14}/> Munka
              </button>
              <button className={entryType === 'purchase' ? 'active' : ''} onClick={() => setEntryType('purchase')}>
                <Icon name="receipt" size={14}/> Csak beszerzés
              </button>
            </div>

            <div className="field">
              <label className="label">Dátum</label>
              <input type="date" className="input" value={date} onChange={e => setDate(e.target.value)} />
            </div>

            {/* Munka csapatok (tiers) */}
            {entryType === 'labor' && (
              <div className="stack-2">
                <div className="row between">
                  <label className="label" style={{ margin: 0 }}>Csapatok</label>
                  {tiers.length > 0 && (
                    <span className="muted" style={{ fontSize: 11, whiteSpace: 'nowrap' }}>
                      össz. {totalWorkers} fő · {totalHours} óra
                    </span>
                  )}
                </div>
                {tiers.map((t, i) => (
                  <div key={i} className="card" style={{ padding: 10, background: 'var(--surface-2)' }}>
                    <div className="row between" style={{ marginBottom: 8 }}>
                      <span className="mono" style={{ fontSize: 11, color: 'var(--ink-3)', whiteSpace: 'nowrap' }}>
                        {tiers.length > 1 ? `${i + 1}. csapat` : 'Munkaóra'}
                      </span>
                      {tiers.length > 1 && (
                        <button className="btn ghost sm" onClick={() => removeTier(i)} style={{ padding: 4, color: 'var(--danger)' }} aria-label="csapat törlése">
                          <Icon name="x" size={14}/>
                        </button>
                      )}
                    </div>
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
                      <div className="field" style={{ margin: 0 }}>
                        <label className="label">Fő</label>
                        <Stepper value={t.workers} onChange={v => updateTier(i, { workers: v })} min={1} max={20}/>
                      </div>
                      <div className="field" style={{ margin: 0 }}>
                        <label className="label">Óra / fő</label>
                        <Stepper value={t.hours} onChange={v => updateTier(i, { hours: v })} min={1} max={16}/>
                      </div>
                    </div>
                    <div className="row between" style={{ marginTop: 8, fontSize: 12, gap: 8 }}>
                      <span className="muted" style={{ whiteSpace: 'nowrap' }}>{t.workers} × {t.hours}ó × {window.formatHufShort(user.hourlyRate)} Ft</span>
                      <span className="num" style={{ fontWeight: 500, whiteSpace: 'nowrap' }}>
                        {window.formatHuf((t.workers || 0) * (t.hours || 0) * user.hourlyRate)}
                      </span>
                    </div>
                  </div>
                ))}
                <button className="btn ghost sm" onClick={addTier}
                  style={{ alignSelf: 'flex-start', borderStyle: 'dashed', borderWidth: 1, borderColor: 'var(--line)', padding: '8px 12px', whiteSpace: 'nowrap' }}>
                  <Icon name="plus" size={14}/> Új csapat
                </button>
              </div>
            )}

            {/* Anyag / beszerzés ár */}
            <div className="field">
              <label className="label">
                {entryType === 'purchase' ? 'Beszerzés / számla összege' : 'Anyagköltség (opcionális)'}
              </label>
              <div className="row" style={{ gap: 8, alignItems: 'center' }}>
                <input type="number" className="input" placeholder="0" value={materialCost || ''} onChange={e => setMaterial(parseInt(e.target.value) || 0)} style={{ flex: 1, minWidth: 0 }}/>
                <span className="mono muted" style={{ fontSize: 13, whiteSpace: 'nowrap' }}>Ft</span>
              </div>
            </div>
          </div>
        )}

        {/* 4. Leírás + fotó */}
        {taskId && (
          <div className="stack-2">
            <div className="eyebrow">4 · Leírás és fotók</div>
            <div className="field">
              <label className="label">Mit csináltatok? <span className="muted">(rövid leírás)</span></label>
              <textarea className="textarea" placeholder="Pl. Hálószoba fal újraépítés, 2. nap. Tégla rakás befejezve, vakolás kezdve."
                value={description} onChange={e => setDesc(e.target.value)} rows={3}/>
            </div>

            <div className="field">
              <label className="label">Fotók a munkáról / számláról</label>
              <input ref={photoInputRef} type="file" multiple accept="image/*" capture="environment"
                style={{ display: 'none' }} onChange={onPhotoPick}/>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8 }}>
                <button className="photo-ph tap" onClick={() => photoInputRef.current?.click()}
                  style={{ aspectRatio: '1', borderColor: 'var(--accent)', color: 'var(--accent-d)', borderStyle: 'dashed', flexDirection: 'column', gap: 4 }}>
                  <Icon name="camera" size={22}/>
                  <span style={{ fontSize: 10, fontWeight: 600 }}>FOTÓ</span>
                </button>
                {photos.map(p => (
                  <div key={p.id} className="photo-ph" style={{ aspectRatio: '1', borderStyle: 'solid', background: 'var(--ink-4)', color: 'white', borderColor: 'transparent', position: 'relative', overflow: 'hidden' }}>
                    {p.previewUrl
                      ? <img src={p.previewUrl} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }}/>
                      : <Icon name="image" size={20}/>}
                    <button className="bare" onClick={() => setPhotos(photos.filter(x => x.id !== p.id))}
                      style={{ position: 'absolute', top: 2, right: 2, background: 'rgba(0,0,0,0.6)', color: 'white', borderRadius: 999, width: 20, height: 20, display: 'flex', alignItems: 'center', justifyContent: 'center' }}
                      aria-label="fotó törlése">
                      <Icon name="x" size={12}/>
                    </button>
                  </div>
                ))}
              </div>
              <div className="muted" style={{ fontSize: 11, marginTop: 6 }}>Több fotó is feltölthető. A jóváhagyó látja majd.</div>
            </div>
          </div>
        )}
      </div>

      {/* Sticky CTA */}
      <div className="sticky-cta" style={{ position: 'fixed', left: 0, right: 0, bottom: 0, background: 'linear-gradient(180deg, transparent, var(--bg) 30%)', borderTop: '1px solid var(--line)' }}>
        {taskId && (
          <div className="card" style={{ padding: 10, marginBottom: 10, background: 'var(--ink)', color: 'var(--bg)', border: 'none' }}>
            <div className="row between" style={{ gap: 8 }}>
              <span style={{ fontSize: 12, opacity: 0.7, whiteSpace: 'nowrap' }}>Összesen</span>
              <span className="num" style={{ fontSize: 20, fontWeight: 600, whiteSpace: 'nowrap' }}>{window.formatHuf(total)}</span>
            </div>
          </div>
        )}
        <button className="btn accent full lg" disabled={!canSubmit}
          style={{ opacity: canSubmit ? 1 : 0.4, whiteSpace: 'nowrap' }}
          onClick={() => onSubmit({
            phaseId, parentTaskId: taskId, date, entryType,
            tiers: entryType === 'labor' ? tiers : [],
            hourlyRate: user.hourlyRate, materialCost, description,
            photos: photos.length,
            photoFiles: photos.map(p => p.file).filter(Boolean),
          })}>
          <Icon name="check" size={18} stroke={2.4}/>
          Beküldés
        </button>
      </div>
    </div>
  );
};

const Stepper = ({ value, onChange, min = 0, max = 999, step = 1 }) => (
  <div className="stepper">
    <button onClick={() => onChange(Math.max(min, value - step))} aria-label="csökkent">−</button>
    <input type="number" value={value} onChange={e => {
      const v = parseInt(e.target.value);
      if (!isNaN(v)) onChange(Math.max(min, Math.min(max, v)));
    }}/>
    <button onClick={() => onChange(Math.min(max, value + step))} aria-label="növel">+</button>
  </div>
);

const ContractorHistory = ({ user }) => {
  const [filter, setFilter] = React.useState('all');
  const myLogs = window.WORK_LOGS.filter(l => l.contractorId === user.id).slice().reverse();
  const filtered = filter === 'all' ? myLogs : myLogs.filter(l => l.status === filter);
  const counts = {
    all: myLogs.length,
    pending: myLogs.filter(l => l.status === 'pending').length,
    approved: myLogs.filter(l => l.status === 'approved').length,
    rejected: myLogs.filter(l => l.status === 'rejected').length,
  };
  return (
    <div className="main fade-in">
      <h2>Teljesítéseim</h2>
      <div className="tabs">
        {[
          { k: 'all', l: 'Mind' },
          { k: 'pending', l: 'Várakozik' },
          { k: 'approved', l: 'Jóváhagyva' },
          { k: 'rejected', l: 'Elutasítva' },
        ].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 => <LogCard key={l.id} log={l}/>)}
        {filtered.length === 0 && <div className="muted" style={{ padding: 20, textAlign: 'center', fontSize: 13 }}>Nincs ilyen teljesítés.</div>}
      </div>
    </div>
  );
};

Object.assign(window, { ContractorHome, Logger, ContractorHistory, LogCard, Stepper });
