// desktop-views.jsx  Dashboard + Planner + Team + Structure views

//  Dashboard 
function DesktopDashboard({ user, goPlanner, goStructure }) {
  const ctx = useTurni();
  if (ctx.isAdminRole(user)) return <DesktopAdminDashboard user={user} goStructure={goStructure} />;

  const currentTeam = ctx.currentTeam;

  // Dynamic KPI calculations
  const HOURS = { morning: 6, mid: 6, evening: 6, close: 5.5, off: 0, ferie: 0 };
  const legacyOrBlockHours = (cell) => {
    if (cell && typeof cell === 'object' && Array.isArray(cell.blocks)) {
      return cell.blocks.reduce((sum, b) => sum + Math.max(0, (timeToMinutes(b.end) - timeToMinutes(b.start)) / 60), 0);
    }
    return HOURS[cell] || 0;
  };
  const totalPlanned = currentTeam.reduce((s, e) =>
    s + (ctx.schedule[e.id] || []).reduce((x, k) => x + legacyOrBlockHours(k), 0), 0);
  const expected = TU_WEEK_DATES.map((_, i) => expectedHoursForDay(ctx.currentStore, i));
  const dailyTotal = TU_WEEK_DATES.map((_, i) =>
    currentTeam.reduce((s, e) => s + legacyOrBlockHours((ctx.schedule[e.id] || [])[i] || 'off'), 0));
  const expectedTotal = expected.reduce((a, b) => a + b, 0);
  const gaps = dailyTotal.reduce((s, t, i) => s + Math.max(0, expected[i] - t), 0);
  const coveragePct = expectedTotal > 0 ? Math.round((totalPlanned / expectedTotal) * 100) : 0;
  const onFerie = currentTeam.filter(e => (ctx.schedule[e.id] || []).includes('ferie')).length;

  return (
    <>
      <DesktopTopbar
        title={`Buongiorno, ${ctx.currentStore?.city || 'Admin'}`}
        subtitle={`${TU_WEEK_LABEL} · ${ctx.currentStore?.name}`}
        actions={<button className="tu-btn tu-btn-primary" onClick={goPlanner}><TuIcon.plus size={16}/> Pianifica settimana</button>}
      />
      <div style={{ flex: 1, overflow: 'auto', padding: 28, display: 'flex', flexDirection: 'column', gap: 20 }}>
        {/* KPI */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16 }}>
          <KpiCard label="Ore pianificate"  value={`${totalPlanned}`}       delta={`${gaps > 0 ? gaps + ' buchi' : 'ok'}`}  deltaLabel="questa sett." trend={gaps > 0 ? 'warn' : 'up'} accent/>
          <KpiCard label="Copertura turni"  value={`${coveragePct}%`}       delta={`${gaps > 0 ? gaps + ' buchi' : ' Piena'}`} deltaLabel="da coprire" trend={gaps > 0 ? 'warn' : 'up'}/>
          <KpiCard label="Addetti in store" value={`${currentTeam.length}`} delta={`${currentTeam.filter(e => (ctx.schedule[e.id] || [])[0] !== 'off').length} oggi`} deltaLabel="in turno lun" trend="flat"/>
          <KpiCard label="In ferie"         value={`${onFerie}`}            delta={onFerie > 0 ? 'questa sett.' : 'nessuno'} deltaLabel="" trend="flat"/>
        </div>

        {/* Coverage (full width) */}
        <div className="tu-card" style={{ padding: 22 }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 16 }}>
            <div>
              <h2 className="tu-h2">Copertura giornaliera</h2>
              <div className="tu-mute" style={{ fontSize: 12.5, marginTop: 2 }}>Ore previste vs ore programmate · {TU_WEEK_LABEL}</div>
            </div>
          </div>
          <CoverageChart dailyTotal={dailyTotal} expected={expected}/>
          <div style={{ display: 'flex', gap: 18, marginTop: 14, fontSize: 12, color: 'var(--ink-3)' }}>
            <Legend swatch="var(--primary)" label="Programmate"/>
            <Legend swatch="var(--bg-2)" border label="Previste"/>
            {gaps > 0 && <Legend swatch="var(--danger)" label="Buchi" dot/>}
          </div>
        </div>

        {/* Squadra di oggi (full width) */}
        <div className="tu-card" style={{ padding: 22 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
            <h2 className="tu-h2">Squadra di oggi</h2>
            <span style={{ fontSize: 12, color: 'var(--ink-3)' }}>{TU_DAYS_SHORT[TU_TODAY_INDEX]} {TU_TODAY.getDate()} {TU_MONTHS[TU_TODAY.getMonth()]}</span>
          </div>
          {currentTeam.length === 0 && (
            <div style={{ padding: 20, textAlign: 'center', color: 'var(--ink-3)', fontSize: 13 }}>Nessun addetto in questo store.</div>
          )}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {currentTeam.slice(0,6).map((m, i) => {
              const kind = (ctx.schedule[m.id] || [])[TU_TODAY_INDEX] || 'off';
              const k = TU_SHIFT_KINDS[typeof kind === 'string' ? kind : (kind?.preset || 'work')] || TU_SHIFT_KINDS.work;
              return (
                <div key={m.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '8px 4px', borderBottom: i < Math.min(currentTeam.length, 6) - 1 ? '1px dashed var(--line)' : 0 }}>
                  <TuAvatar name={m.name} size={32}/>
                  <div style={{ flex: 1, lineHeight: 1.2 }}>
                    <div style={{ fontSize: 13.5, fontWeight: 600 }}>{m.name}</div>
                    <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{m.role}</div>
                  </div>
                  <div className={`tu-shift ${k.cls}`} style={{ padding: '6px 10px', minWidth: 110, textAlign: 'center' }}>
                    <div style={{ fontSize: 11.5 }}>{k.label}</div>
                    {k.start && <div style={{ fontSize: 11, opacity: .75 }}>{k.start}-{k.end}</div>}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </>
  );
}

function DesktopAdminDashboard({ user, goStructure }) {
  const ctx = useTurni();
  const superAdmin = ctx.isSuperAdminRole(user);
  const storeIds = ctx.stores.map(s => s.id);
  const staffedStores = ctx.stores.filter(s => ctx.team.some(e => e.storeId === s.id)).length;
  const emptyStores = ctx.stores.length - staffedStores;
  const pending = superAdmin ? ctx.pendingApprovals.length : 0;
  const todayIn = ctx.team.filter(e => {
    const kind = (ctx.schedule[e.id] || [])[TU_TODAY_INDEX];
    return kind && kind !== 'off' && kind !== 'ferie';
  }).length;

  const brandRows = ctx.brands.map(brand => {
    const companies = ctx.companies.filter(c => c.brandId === brand.id);
    const cIds = companies.map(c => c.id);
    const stores = ctx.stores.filter(s => cIds.includes(s.companyId));
    const employees = ctx.team.filter(e => stores.some(s => s.id === e.storeId));
    return { brand, companies, stores, employees };
  });
  const attention = [
    ...(pending ? [{ title: `${pending} accessi in attesa`, body: 'Richieste utente da approvare', tone: 'warn' }] : []),
    ...(emptyStores ? [{ title: `${emptyStores} negozi senza addetti`, body: 'Completa il personale o verifica la struttura', tone: 'danger' }] : []),
    ...(!ctx.brands.length ? [{ title: 'Nessun brand configurato', body: 'Crea la struttura aziendale', tone: 'danger' }] : []),
  ];

  return (
    <>
      <DesktopTopbar
        title={superAdmin ? 'Panoramica Super Admin' : 'Panoramica amministrazione'}
        subtitle={`${ctx.holding} · ${superAdmin ? 'controllo piattaforma' : 'vista amministrazione'}`}
        actions={<button className="tu-btn tu-btn-primary" onClick={goStructure}><TuIcon.building size={16}/> Gestisci struttura</button>}
      />
      <div style={{ flex: 1, overflow: 'auto', padding: 28, display: 'flex', flexDirection: 'column', gap: 20 }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 14 }}>
          <KpiCard label="Brand" value={ctx.brands.length} delta="attivi" deltaLabel="" trend="flat" accent/>
          <KpiCard label="Società" value={ctx.companies.length} delta="operative" deltaLabel="" trend="flat"/>
          <KpiCard label="Negozi" value={ctx.stores.length} delta={`${staffedStores} con team`} deltaLabel="" trend={emptyStores ? 'warn' : 'up'}/>
          <KpiCard label="Addetti" value={ctx.team.length} delta={`${todayIn} oggi`} deltaLabel="" trend="flat"/>
          <KpiCard label="Accessi" value={pending} delta={pending ? 'da approvare' : 'ok'} deltaLabel="" trend={pending ? 'warn' : 'up'}/>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1.25fr .75fr', gap: 20, alignItems: 'start' }}>
          <div className="tu-card" style={{ padding: 22 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 18 }}>
              <div>
                <h2 className="tu-h2">Struttura gruppo</h2>
                <div className="tu-mute" style={{ fontSize: 12.5, marginTop: 3 }}>Brand, società operative, negozi e addetti</div>
              </div>
              <button className="tu-btn tu-btn-soft" onClick={goStructure}><TuIcon.arrowR size={15}/> Apri</button>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {brandRows.map(({ brand, companies, stores, employees }) => (
                <div key={brand.id} style={{ display: 'grid', gridTemplateColumns: '1fr auto auto auto', gap: 14, alignItems: 'center', padding: '14px 16px', border: '1px solid var(--line)', borderRadius: 14, background: 'var(--bg)' }}>
                  <div>
                    <div style={{ fontSize: 15, fontWeight: 800 }}>{brand.name}</div>
                    <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginTop: 2 }}>{companies.length} società operative</div>
                  </div>
                  <AdminMiniStat label="Negozi" value={stores.length}/>
                  <AdminMiniStat label="Addetti" value={employees.length}/>
                  <span className={employees.length ? 'tu-chip tu-chip-ok' : 'tu-chip tu-chip-warn'}>{employees.length ? 'Attivo' : 'Vuoto'}</span>
                </div>
              ))}
            </div>
          </div>

          <div className="tu-card" style={{ padding: 22 }}>
            <h2 className="tu-h2" style={{ marginBottom: 14 }}>Da controllare</h2>
            {attention.length === 0 ? (
              <div style={{ padding: 18, borderRadius: 14, background: '#DFF1E6', color: '#1E6B43', fontWeight: 700, fontSize: 13 }}>Nessuna criticità aperta.</div>
            ) : (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {attention.map((item, i) => (
                  <div key={i} style={{ padding: 14, borderRadius: 14, background: item.tone === 'danger' ? '#FBE0DD' : '#FCEBC9', color: item.tone === 'danger' ? '#9B2A21' : '#855300' }}>
                    <div style={{ fontSize: 13.5, fontWeight: 800 }}>{item.title}</div>
                    <div style={{ fontSize: 12, marginTop: 3, opacity: .85 }}>{item.body}</div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      </div>
    </>
  );
}

function AdminMiniStat({ label, value }) {
  return (
    <div style={{ minWidth: 72, textAlign: 'right' }}>
      <div style={{ fontSize: 18, fontWeight: 850 }}>{value}</div>
      <div style={{ fontSize: 10.5, color: 'var(--ink-3)', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.04em' }}>{label}</div>
    </div>
  );
}

function KpiCard({ label, value, delta, deltaLabel, trend, accent }) {
  const trendColor = { up: 'var(--ok)', down: 'var(--ok)', warn: 'var(--warn)', flat: 'var(--ink-3)' }[trend];
  const arrow = { up: 'OK', down: 'OK', warn: '!', flat: '·' }[trend];
  return (
    <div className="tu-card" style={{ padding: 18, position: 'relative', overflow: 'hidden' }}>
      {accent && <div style={{ position: 'absolute', inset: 0, top: 'auto', height: 3, background: 'linear-gradient(90deg, var(--primary), var(--primary-deep))' }}/>}
      <div className="tu-tiny">{label}</div>
      <div style={{ fontSize: 30, fontWeight: 800, letterSpacing: '-.025em', marginTop: 4 }}>{value}</div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 6, fontSize: 12 }}>
        <span style={{ color: trendColor, fontWeight: 700 }}>{arrow} {delta}</span>
        <span style={{ color: 'var(--ink-3)' }}>{deltaLabel}</span>
      </div>
    </div>
  );
}

function CoverageChart({ dailyTotal, expected }) {
  const max = 60;
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', gap: 14, height: 180, padding: '0 4px' }}>
      {TU_DAYS_SHORT.map((d, i) => (
        <div key={d} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
          <div style={{ position: 'relative', width: '100%', height: 150, display: 'flex', alignItems: 'flex-end', justifyContent: 'center' }}>
            <div style={{ position: 'absolute', bottom: 0, width: '70%', height: `${(expected[i]||0)/max*100}%`, background: 'var(--bg-2)', border: '1px dashed var(--line-2)', borderRadius: '8px 8px 0 0' }}/>
            <div style={{ position: 'relative', width: '52%', height: `${(dailyTotal[i]||0)/max*100}%`, background: dailyTotal[i] < expected[i] ? 'var(--danger)' : 'var(--primary)', borderRadius: '8px 8px 0 0' }}>
              {dailyTotal[i] < expected[i] && (
                <div style={{ position: 'absolute', top: -22, left: '50%', transform: 'translateX(-50%)', background: 'var(--danger)', color: '#fff', fontSize: 10.5, fontWeight: 700, padding: '2px 7px', borderRadius: 999, whiteSpace: 'nowrap' }}>
                  -{expected[i] - dailyTotal[i]}h
                </div>
              )}
            </div>
          </div>
          <div style={{ fontSize: 11.5, color: 'var(--ink-3)', fontWeight: 600 }}>{d}</div>
          <div style={{ fontSize: 10.5, color: 'var(--ink-4)' }}>{TU_WEEK_DATES[i]}</div>
        </div>
      ))}
    </div>
  );
}

function Legend({ swatch, label, border, dot }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
      <div style={{ width: dot ? 8 : 14, height: dot ? 8 : 10, borderRadius: dot ? '50%' : 3, background: swatch, border: border ? '1px dashed var(--line-2)' : 'none' }}/>
      <span>{label}</span>
    </div>
  );
}

const PLANNER_DAY_KEYS = ['mon','tue','wed','thu','fri','sat','sun'];
function timeToMinutes(value) {
  const [h, m] = String(value || '00:00').split(':').map(n => parseInt(n, 10) || 0);
  return h * 60 + m;
}
function minutesToTime(value) {
  const v = Math.max(0, Math.min(24 * 60, Math.round(value / 15) * 15));
  const h = String(Math.floor(v / 60)).padStart(2, '0');
  const m = String(v % 60).padStart(2, '0');
  return `${h}:${m}`;
}
function hoursBetween(start, end) {
  return Math.max(0, (timeToMinutes(end) - timeToMinutes(start)) / 60);
}
function openingBlocksFor(store, dayIdx) {
  const hours = store?.openingHours || window.DEFAULT_OPENING_HOURS || {};
  return (hours[PLANNER_DAY_KEYS[dayIdx]] || [])
    .filter(b => b?.start && b?.end && timeToMinutes(b.end) > timeToMinutes(b.start))
    .sort((a, b) => timeToMinutes(a.start) - timeToMinutes(b.start));
}
function openingLabel(blocks) {
  return blocks.length ? blocks.map(b => `${b.start}-${b.end}`).join(' / ') : 'Chiuso';
}
function dynamicShiftMeta(store, dayIdx, kind) {
  const base = TU_SHIFT_KINDS[kind] || TU_SHIFT_KINDS.off;
  if (kind === 'off' || kind === 'ferie') return base;
  const blocks = openingBlocksFor(store, dayIdx);
  if (!blocks.length) return { ...TU_SHIFT_KINDS.off, label: 'Chiuso', disabled: true };

  if (blocks.length > 1) {
    if (kind === 'morning') {
      const b = blocks[0];
      return { ...base, label: 'Mattina', start: b.start, end: b.end, hours: hoursBetween(b.start, b.end) };
    }
    if (kind === 'evening' || kind === 'close') {
      const b = blocks[blocks.length - 1];
      return { ...base, label: kind === 'close' ? 'Chiusura' : 'Pomeriggio', start: b.start, end: b.end, hours: hoursBetween(b.start, b.end) };
    }
    const first = blocks[0];
    const last = blocks[blocks.length - 1];
    return { ...base, label: 'Spezzato', start: first.start, end: last.end, hours: blocks.reduce((sum, b) => sum + hoursBetween(b.start, b.end), 0) };
  }

  const b = blocks[0];
  const start = timeToMinutes(b.start);
  const end = timeToMinutes(b.end);
  const span = end - start;
  if (kind === 'morning') {
    const shiftEnd = minutesToTime(Math.min(end, start + Math.min(6 * 60, span)));
    return { ...base, label: 'Apertura', start: b.start, end: shiftEnd, hours: hoursBetween(b.start, shiftEnd) };
  }
  if (kind === 'evening') {
    const shiftStart = minutesToTime(Math.max(start, end - Math.min(6 * 60, span)));
    return { ...base, label: 'Pomeriggio', start: shiftStart, end: b.end, hours: hoursBetween(shiftStart, b.end) };
  }
  if (kind === 'close') {
    const shiftStart = minutesToTime(Math.max(start, end - Math.min(5.5 * 60, span)));
    return { ...base, label: 'Chiusura', start: shiftStart, end: b.end, hours: hoursBetween(shiftStart, b.end) };
  }
  const midLength = Math.min(6 * 60, span);
  const midStart = minutesToTime(start + Math.max(0, (span - midLength) / 2));
  const midEnd = minutesToTime(Math.min(end, timeToMinutes(midStart) + midLength));
  return { ...base, label: 'Centrale', start: midStart, end: midEnd, hours: hoursBetween(midStart, midEnd) };
}
function shiftOptionsForDay(store, dayIdx) {
  const statuses = ['off','ferie','malattia','permesso','festivo','formazione','riunione','recupero']
    .map(k => [k, TU_STATUS_KINDS[k]]);
  if (!openingBlocksFor(store, dayIdx).length) return statuses;
  return ['morning','mid','evening','close'].map(k => [k, dynamicShiftMeta(store, dayIdx, k)]).concat(statuses);
}
function expectedHoursForDay(store, dayIdx) {
  const openHours = openingBlocksFor(store, dayIdx).reduce((sum, b) => sum + hoursBetween(b.start, b.end), 0);
  return openHours ? Math.round(openHours * 2) : 0;
}
function storeCode(stores, storeId, currentStoreId) {
  if (!storeId || storeId === currentStoreId) return '';
  const s = stores.find(x => x.id === storeId);
  return s?.short?.split('-')[0] || s?.name?.split(' ')[0] || '';
}
function blocksForPreset(store, dayIdx, kind) {
  const blocks = openingBlocksFor(store, dayIdx);
  if (!blocks.length) return [];
  if (kind === 'morning') return [blocks[0]];
  if (kind === 'evening' || kind === 'close') return [blocks[blocks.length - 1]];
  if (blocks.length > 1 && kind === 'mid') return blocks;
  const meta = dynamicShiftMeta(store, dayIdx, kind);
  return meta.start ? [{ start: meta.start, end: meta.end }] : [];
}
function makeWorkShift(store, dayIdx, kind, storeId) {
  const blocks = blocksForPreset(store, dayIdx, kind).map(b => ({ start: b.start, end: b.end, storeId }));
  return blocks.length ? { status: 'work', preset: kind, blocks } : 'off';
}
function shiftStatus(cell) {
  if (!cell || cell === 'off') return 'off';
  if (cell === 'ferie') return 'ferie';
  if (typeof cell === 'object') return cell.status || 'work';
  if (typeof cell === 'string' && TU_STATUS_KINDS[cell]) return cell; // riposo/chiuso/malattia/festivo/...
  return 'work';
}
function normalizeShiftCell(cell, store, dayIdx, currentStoreId) {
  const status = shiftStatus(cell);
  if (status !== 'work') return { status, blocks: [] };
  if (typeof cell === 'object' && Array.isArray(cell.blocks)) return { status: 'work', blocks: cell.blocks };
  return { status: 'work', blocks: makeWorkShift(store, dayIdx, cell, currentStoreId).blocks || [] };
}
function shiftCellHours(cell, store, dayIdx, currentStoreId) {
  return normalizeShiftCell(cell, store, dayIdx, currentStoreId).blocks.reduce((sum, b) => sum + hoursBetween(b.start, b.end), 0);
}
function shiftCellLabel(cell, store, dayIdx, stores, currentStoreId) {
  const normalized = normalizeShiftCell(cell, store, dayIdx, currentStoreId);
  if (normalized.status === 'ferie') return 'Ferie';
  if (normalized.status === 'off') return openingBlocksFor(store, dayIdx).length ? 'Riposo' : 'Chiuso';
  if (normalized.status !== 'work') return (TU_STATUS_KINDS[normalized.status] || {}).label || normalized.status;
  return normalized.blocks.map(b => `${b.start}-${b.end}${storeCode(stores, b.storeId, currentStoreId) ? ' ' + storeCode(stores, b.storeId, currentStoreId) : ''}`).join(' / ');
}
function shiftCellClass(cell, store, dayIdx) {
  const normalized = normalizeShiftCell(cell, store, dayIdx, store?.id);
  if (normalized.status !== 'work') return (TU_STATUS_KINDS[normalized.status] || {}).cls || 'tu-shift-off';
  return normalized.blocks.length > 1 ? 'tu-shift-mid' : 'tu-shift-morning';
}
function employeeBlocksForDay(emp, dayIdx, ctx) {
  const homeStore = ctx.stores.find(s => s.id === emp.storeId) || ctx.currentStore;
  const cell = (ctx.schedule[emp.id] || [])[dayIdx] || 'off';
  const normalized = normalizeShiftCell(cell, homeStore, dayIdx, emp.storeId);
  if (normalized.status !== 'work') return [];
  return normalized.blocks.map(b => ({ ...b, storeId: b.storeId || emp.storeId }));
}
function employeesInStoreForDay(storeId, dayIdx, ctx) {
  return ctx.team
    .map(emp => ({ emp, blocks: employeeBlocksForDay(emp, dayIdx, ctx).filter(b => b.storeId === storeId) }))
    .filter(row => row.blocks.length > 0);
}
function PlannerStoresDaySidebar({ user, selectedDay, setSelectedDay, compact = false }) {
  const ctx = useTurni();
  const visibleStoreIds = ctx.visibleStoreIds(user);
  const visibleStores = ctx.stores.filter(s => visibleStoreIds.includes(s.id));
  const editableStoreIds = ctx.editableStoreIds(user);

  return (
    <aside style={{ width: 340, flexShrink: 0, borderRight: '1px solid var(--line)', background: 'var(--surface)', display: 'flex', flexDirection: 'column', minHeight: 0 }}>
      <div style={{ padding: '16px 16px 12px', borderBottom: '1px solid var(--line)' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, marginBottom: 12 }}>
          <div>
            <div style={{ fontSize: 13, fontWeight: 900, color: 'var(--ink)' }}>Negozi</div>
            <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 2 }}>Operatori presenti nel giorno</div>
          </div>
          <span className="tu-chip" style={{ fontSize: 11 }}>{visibleStores.length}</span>
        </div>
        {compact ? (
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, height: 34, padding: '0 11px', borderRadius: 999, background: 'var(--primary-soft)', color: 'var(--primary-deep)', fontSize: 12, fontWeight: 850 }}>
            {TU_DAYS_LONG[selectedDay]} {TU_WEEK_DATES[selectedDay]} {TU_MONTHS[new Date(TU_WEEK_MONDAY.getTime() + selectedDay * 86400000).getMonth()]}
          </div>
        ) : (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 4 }}>
            {TU_DAYS_SHORT.map((d, i) => {
              const active = selectedDay === i;
              return (
                <button key={d} onClick={() => setSelectedDay(i)} title={TU_DAYS_LONG[i]}
                  style={{ height: 38, borderRadius: 8, border: `1px solid ${active ? 'var(--primary)' : 'var(--line)'}`, background: active ? 'var(--primary)' : 'var(--bg)', color: active ? '#fff' : 'var(--ink-2)', fontSize: 10.5, fontWeight: 850, cursor: 'pointer', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', lineHeight: 1.05 }}>
                  <span>{d}</span>
                  <span style={{ fontSize: 9, opacity: .78 }}>{TU_WEEK_DATES[i]}</span>
                </button>
              );
            })}
          </div>
        )}
      </div>

      <div style={{ flex: 1, overflow: 'auto', padding: 12, display: 'flex', flexDirection: 'column', gap: 10 }}>
        {visibleStores.map(store => {
          const active = store.id === ctx.currentStoreId;
          const readOnly = !editableStoreIds.includes(store.id);
          const rows = employeesInStoreForDay(store.id, selectedDay, ctx);
          const company = ctx.companies.find(c => c.id === store.companyId);
          const open = openingBlocksFor(store, selectedDay);
          return (
            <button key={store.id} onClick={() => ctx.setCurrentStoreId(store.id)}
              style={{ width: '100%', textAlign: 'left', border: `1px solid ${active ? 'var(--primary)' : 'var(--line)'}`, background: active ? 'var(--primary-soft)' : 'var(--bg)', color: 'var(--ink)', borderRadius: 12, padding: 0, cursor: 'pointer', overflow: 'hidden', boxShadow: active ? '0 8px 20px rgba(42,111,219,.12)' : 'none' }}>
              <div style={{ display: 'grid', gridTemplateColumns: '38px 1fr auto', gap: 10, alignItems: 'center', padding: '11px 12px', borderBottom: rows.length ? '1px solid var(--line)' : 0 }}>
                <span style={{ width: 34, height: 34, borderRadius: 9, background: active ? 'var(--primary)' : 'var(--surface)', color: active ? '#fff' : 'var(--ink-3)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 10, fontWeight: 900 }}>{store.short?.slice(0,2) || store.name[0]}</span>
                <span style={{ minWidth: 0 }}>
                  <span style={{ display: 'block', fontSize: 13.5, fontWeight: 850, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', color: active ? 'var(--primary-deep)' : 'var(--ink)' }}>{store.name}</span>
                  <span style={{ display: 'block', fontSize: 10.8, color: active ? 'var(--primary-deep)' : 'var(--ink-3)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                    {company?.name || store.city} · {open.length ? openingLabel(open) : 'chiuso'}
                  </span>
                </span>
                <span style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', minWidth: 28, height: 24, borderRadius: 999, background: rows.length ? '#DFF1E6' : 'var(--surface)', color: rows.length ? '#1E6B43' : 'var(--ink-4)', fontSize: 11, fontWeight: 900 }}>{rows.length}</span>
              </div>
              {rows.length > 0 ? (
                <div style={{ padding: '8px 10px 10px', display: 'flex', flexDirection: 'column', gap: 6 }}>
                  {rows.slice(0, 5).map(({ emp, blocks }) => (
                    <div key={emp.id} style={{ display: 'grid', gridTemplateColumns: '26px 1fr auto', gap: 8, alignItems: 'center' }}>
                      <TuAvatar name={emp.name} size={26}/>
                      <span style={{ minWidth: 0 }}>
                        <span style={{ display: 'block', fontSize: 12, fontWeight: 750, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{emp.name}</span>
                        <span style={{ display: 'block', fontSize: 10.5, color: 'var(--ink-4)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{emp.role}</span>
                      </span>
                      <span style={{ fontSize: 10.5, color: 'var(--ink-3)', fontWeight: 800, whiteSpace: 'nowrap' }}>
                        {blocks.map(b => `${b.start}-${b.end}`).join(' / ')}
                      </span>
                    </div>
                  ))}
                  {rows.length > 5 && <div style={{ fontSize: 11, color: 'var(--ink-3)', fontWeight: 750, paddingLeft: 34 }}>+{rows.length - 5} altri operatori</div>}
                </div>
              ) : (
                <div style={{ padding: '0 12px 11px 60px', fontSize: 11.5, color: 'var(--ink-4)', fontWeight: 650 }}>
                  {open.length ? 'Nessun operatore pianificato' : 'Negozio chiuso'}
                </div>
              )}
              {readOnly && <div style={{ padding: '0 12px 10px 60px', fontSize: 10.5, color: 'var(--ink-4)', fontWeight: 800 }}>Sola lettura</div>}
            </button>
          );
        })}
      </div>
    </aside>
  );
}
const sheetDayHeaderStyle = {
  padding: '10px 10px',
  borderLeft: '1px solid var(--line)',
  borderBottom: '1px solid var(--line)',
  background: 'var(--surface)',
  textAlign: 'center',
  minHeight: 58,
};
const sheetCellStyle = {
  padding: '8px 9px',
  borderLeft: '1px solid var(--line)',
  borderBottom: '1px solid var(--line)',
  position: 'relative',
  minHeight: 54,
  background: '#fff',
};
function PlannerScopeBoard({ user }) {
  const ctx = useTurni();
  const visibleBrandIds = ctx.visibleBrandIds(user);
  const visibleStoreIds = ctx.visibleStoreIds(user);
  const visibleBrands = ctx.brands.filter(b => visibleBrandIds.includes(b.id));
  const visibleCompanies = ctx.companies.filter(c => ctx.visibleCompanyIds(user).includes(c.id));

  return (
    <div style={{ padding: '14px 28px 12px', background: 'var(--surface)', borderBottom: '1px solid var(--line)' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 14, marginBottom: 10 }}>
        <div>
          <div style={{ fontSize: 12, fontWeight: 800, color: 'var(--ink-2)' }}>Pianificazione per brand</div>
          <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>Seleziona un negozio: sotto appare la sua settimana con gli addetti abituali.</div>
        </div>
        <span className="tu-chip" style={{ fontSize: 11 }}>{visibleStoreIds.length} negozi visibili</span>
      </div>
      <div style={{ display: 'flex', gap: 12, overflowX: 'auto', paddingBottom: 2 }}>
        {visibleBrands.map(brand => {
          const brandCompanies = visibleCompanies.filter(c => c.brandId === brand.id);
          const brandStores = ctx.stores.filter(s => visibleStoreIds.includes(s.id) && brandCompanies.some(c => c.id === s.companyId));
          if (!brandStores.length) return null;
          return (
            <div key={brand.id} style={{ flex: '0 0 330px', border: '1px solid var(--line)', borderRadius: 14, background: 'var(--bg)', overflow: 'hidden' }}>
              <div style={{ padding: '10px 12px', borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'center', gap: 9 }}>
                <TuLogoMark size={28}/>
                <div style={{ minWidth: 0 }}>
                  <div className="tu-tiny">Brand</div>
                  <div style={{ fontSize: 14, fontWeight: 800, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{brand.name}</div>
                </div>
                <span style={{ marginLeft: 'auto', fontSize: 11, color: 'var(--ink-3)', fontWeight: 700 }}>{brandStores.length}</span>
              </div>
              <div style={{ padding: 8, display: 'flex', flexDirection: 'column', gap: 6, maxHeight: 170, overflow: 'auto' }}>
                {brandStores.map(store => {
                  const active = store.id === ctx.currentStoreId;
                  const people = ctx.team.filter(e => e.storeId === store.id).length;
                  return (
                    <button key={store.id} onClick={() => ctx.setCurrentStoreId(store.id)}
                      style={{ display: 'grid', gridTemplateColumns: '42px 1fr auto', alignItems: 'center', gap: 8, width: '100%', border: `1px solid ${active ? 'var(--primary)' : 'var(--line)'}`, background: active ? 'var(--primary-soft)' : 'var(--surface)', color: active ? 'var(--primary-deep)' : 'var(--ink)', borderRadius: 10, padding: '8px 9px', cursor: 'pointer', textAlign: 'left' }}>
                      <span style={{ width: 34, height: 28, borderRadius: 8, background: active ? 'var(--primary)' : 'var(--bg-2)', color: active ? '#fff' : 'var(--ink-3)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 10, fontWeight: 800 }}>{store.short?.slice(0,2) || store.name[0]}</span>
                      <span style={{ minWidth: 0 }}>
                        <span style={{ display: 'block', fontSize: 12.5, fontWeight: 800, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{store.name}</span>
                        <span style={{ display: 'block', fontSize: 10.5, color: active ? 'var(--primary-deep)' : 'var(--ink-3)' }}>{store.city} · {people} addetti</span>
                      </span>
                      {active && <TuIcon.check size={14}/>}
                    </button>
                  );
                })}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

//  Planner 
function DesktopPlanner({ user }) {
  const ctx = useTurni();
  const currentTeam = ctx.currentTeam;
  const currentStore = ctx.currentStore;
  const assignableStoresForEmployee = (emp) => {
    const companyId = emp.companyId || ctx.stores.find(s => s.id === emp.storeId)?.companyId || currentStore?.companyId;
    return ctx.stores.filter(s => s.companyId === companyId && ctx.editableStoreIds(user).includes(s.id));
  };
  const readOnly = !ctx.canEditStore(user, ctx.currentStoreId);
  const [drag, setDrag] = useState(null);
  const [hoverCell, setHoverCell] = useState(null);
  const [pickerCell, setPickerCell] = useState(null);
  const [selectedDay, setSelectedDay] = useState(0);
  const [confirmMsg, setConfirmMsg] = useState('');
  const handleConfirmWeek = async () => {
    const r = await ctx.confirmWeek?.(ctx.currentStoreId).catch(() => null);
    const n = r?.notified ?? 0;
    setConfirmMsg(n > 0 ? `Notificati ${n} addetti` : 'Nessuna push (Web Push non attivo o nessun addetto)');
    setTimeout(() => setConfirmMsg(''), 4000);
  };

  const totalHoursFor = (emp) => (ctx.schedule[emp.id] || []).reduce((s, k, i) => s + shiftCellHours(k, currentStore, i, ctx.currentStoreId), 0);

  const dropTo = (empId, dayIdx) => {
    if (!drag) return;
    if (!openingBlocksFor(currentStore, dayIdx).length && !['off', 'ferie'].includes(drag.kind)) {
      setDrag(null); setHoverCell(null);
      return;
    }
    if (drag.fromEmp === null) {
      ctx.updateShift(empId, dayIdx, makeWorkShift(currentStore, dayIdx, drag.kind, ctx.currentStoreId));
    } else if (drag.fromEmp === empId) {
      const row = [...(ctx.schedule[empId] || [])];
      const tmp = row[dayIdx]; row[dayIdx] = drag.value || drag.kind; row[drag.fromDay] = tmp;
      row.forEach((k, i) => ctx.updateShift(empId, i, k));
    } else {
      ctx.updateShift(drag.fromEmp, drag.fromDay, 'off');
      ctx.updateShift(empId, dayIdx, drag.value || drag.kind);
    }
    setDrag(null); setHoverCell(null);
  };

  return (
    <>
      <DesktopTopbar
        title="Pianificazione turni"
        subtitle={`${ctx.currentStore?.name || 'Nessun negozio selezionato'} · ${TU_WEEK_LABEL} · ${TU_DAYS_LONG[selectedDay]} ${TU_WEEK_DATES[selectedDay]} ${TU_MONTHS[new Date(TU_WEEK_MONDAY.getTime() + selectedDay * 86400000).getMonth()]}`}
        actions={
          readOnly ? (
            <span className="tu-chip">Sola lettura</span>
          ) : (
            <>
              {confirmMsg && <span className="tu-chip" style={{ background: 'var(--ok-soft)', color: 'var(--ok)' }}>{confirmMsg}</span>}
              <button className="tu-btn tu-btn-ghost"><TuIcon.filter size={16}/> Filtri</button>
              <button className="tu-btn tu-btn-primary" onClick={handleConfirmWeek}><TuIcon.check size={16}/> Conferma settimana</button>
            </>
          )
        }
      />
      <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
        <PlannerStoresDaySidebar user={user} selectedDay={selectedDay} setSelectedDay={setSelectedDay}/>
        <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
        {/* Toolbar */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 20px', borderBottom: '1px solid var(--line)', background: 'var(--surface)' }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 12, fontWeight: 800, color: 'var(--ink-2)' }}>Orari negozio selezionato</div>
            <div title={formatStoreHours(currentStore?.openingHours || ctx.defaultOpeningHours(currentStore?.type || 'street'))} style={{ fontSize: 11.5, color: 'var(--ink-3)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
              {formatStoreHours(currentStore?.openingHours || ctx.defaultOpeningHours(currentStore?.type || 'street'))}
            </div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: 4, border: '1px solid var(--line)', borderRadius: 12, background: 'var(--bg)' }}>
            {TU_DAYS_SHORT.map((d, i) => {
              const active = selectedDay === i;
              return (
                <button key={d} onClick={() => setSelectedDay(i)}
                  style={{ width: 38, height: 30, borderRadius: 8, border: 0, background: active ? 'var(--primary)' : 'transparent', color: active ? '#fff' : 'var(--ink-3)', fontSize: 11, fontWeight: 850, cursor: 'pointer' }}>
                  {d}
                </button>
              );
            })}
          </div>
          {readOnly ? (
            <div className="tu-mute" style={{ fontSize: 11.5, fontWeight: 600 }}>Sola visualizzazione · non puoi modificare i turni di questo negozio</div>
          ) : (
            <>
              <div className="tu-mute" style={{ fontSize: 11.5, fontWeight: 600 }}>Trascina un turno →</div>
              <div style={{ display: 'flex', gap: 6 }}>
                {Object.entries(TU_SHIFT_KINDS).filter(([k]) => k !== 'off' && k !== 'ferie').map(([k, v]) => (
                  <div key={k} draggable onDragStart={() => setDrag({ fromEmp: null, fromDay: null, kind: k })} onDragEnd={() => { setDrag(null); setHoverCell(null); }}
                    className={`tu-shift ${v.cls}`} style={{ cursor: 'grab', padding: '6px 10px', minWidth: 88, textAlign: 'center' }}>
                    <div style={{ fontSize: 11.5 }}>{v.label}</div>
                    <div style={{ fontSize: 10.5, opacity: .75 }}>adattivo</div>
                  </div>
                ))}
              </div>
            </>
          )}
        </div>

        {/* Grid */}
        <div style={{ flex: 1, overflow: 'auto', background: 'var(--bg)', padding: '18px 22px 24px' }}>
          {/* Header */}
          <div style={{ minWidth: 1020, display: 'grid', gridTemplateColumns: '210px repeat(7, minmax(118px, 1fr)) 76px', background: 'var(--surface)', border: '1px solid var(--line)', borderBottom: 0, borderRadius: '14px 14px 0 0', overflow: 'hidden', position: 'sticky', top: 0, zIndex: 2, boxShadow: '0 10px 24px rgba(31,27,23,.08)' }}>
            <div style={{ padding: '12px 14px', background: 'var(--primary)', color: '#fff', fontSize: 11, fontWeight: 900, textAlign: 'left', textTransform: 'uppercase', display: 'flex', alignItems: 'center' }}>Operatori</div>
            {TU_DAYS_SHORT.map((d, i) => (
              <div key={d} style={sheetDayHeaderStyle}>
                <div style={{ fontSize: 11, fontWeight: 800 }}>{(() => { const d = new Date(TU_WEEK_MONDAY.getTime() + i * 86400000); return `${String(d.getDate()).padStart(2,'0')}/${String(d.getMonth()+1).padStart(2,'0')}/${d.getFullYear()}`; })()}</div>
                <div style={{ fontSize: 10, fontWeight: 900, textTransform: 'uppercase', marginTop: 2 }}>{TU_DAYS_LONG[i]}</div>
                <div title={openingLabel(openingBlocksFor(currentStore, i))} style={{ fontSize: 9.5, fontWeight: 600, opacity: .72, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{openingLabel(openingBlocksFor(currentStore, i))}</div>
              </div>
            ))}
            <div style={{ ...sheetDayHeaderStyle, fontSize: 10.5, fontWeight: 900, textTransform: 'uppercase' }}>Ore</div>
          </div>

          {/* Rows */}
          <div style={{ minWidth: 1020, borderLeft: '1px solid var(--line)', borderRight: '1px solid var(--line)', background: '#fff' }}>
            {currentTeam.length === 0 && (
              <div style={{ padding: 48, textAlign: 'center', color: 'var(--ink-3)' }}>Nessun addetto in questo store. Aggiungili dalla sezione Personale.</div>
            )}
            {currentTeam.map((emp, rowIdx) => {
              const total = totalHoursFor(emp);
              const over  = total > emp.hours;
              const row   = ctx.schedule[emp.id] || ['off','off','off','off','off','off','off'];
              return (
                <div key={emp.id} style={{ display: 'grid', gridTemplateColumns: '210px repeat(7, minmax(118px, 1fr)) 76px', background: rowIdx % 2 ? 'rgba(248,247,244,.58)' : '#fff' }}>
                  <div style={{ padding: '10px 12px', borderBottom: '1px solid var(--line)', fontSize: 11, fontWeight: 700, color: '#222', display: 'flex', alignItems: 'center', gap: 10, minHeight: 54 }}>
                    <TuAvatar name={emp.name} size={30}/>
                    <div style={{ minWidth: 0, lineHeight: 1.18 }}>
                      <div style={{ fontSize: 13, fontWeight: 700, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{emp.name}</div>
                      <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{emp.role} · {emp.contract}</div>
                    </div>
                  </div>
                  {row.map((kind, dayIdx) => {
                    const normalized = normalizeShiftCell(kind, currentStore, dayIdx, ctx.currentStoreId);
                    const label = shiftCellLabel(kind, currentStore, dayIdx, ctx.stores, ctx.currentStoreId);
                    const isClosed = !openingBlocksFor(currentStore, dayIdx).length;
                    const isHover = hoverCell && hoverCell.emp === emp.id && hoverCell.day === dayIdx && drag;
                    const isPicker = pickerCell && pickerCell.emp === emp.id && pickerCell.day === dayIdx;
                    return (
                      <div key={dayIdx}
                        onDragOver={readOnly ? undefined : (e => { e.preventDefault(); setHoverCell({ emp: emp.id, day: dayIdx }); })}
                        onDragLeave={readOnly ? undefined : (() => setHoverCell(null))}
                        onDrop={readOnly ? undefined : (() => dropTo(emp.id, dayIdx))}
                        onClick={readOnly ? undefined : (() => setPickerCell(isPicker ? null : { emp: emp.id, day: dayIdx }))}
                        style={{ ...sheetCellStyle, background: isHover ? '#fff8d8' : (isClosed ? 'rgba(248,247,244,.7)' : 'transparent'), cursor: readOnly ? 'default' : 'pointer' }}>
                        {normalized.status === 'off' ? (
                          <div style={{ minHeight: 36, display: 'flex', alignItems: 'center', color: 'var(--ink-4)', fontSize: 11.5, fontWeight: 700 }}>
                            <span style={{ padding: '5px 8px', borderRadius: 999, background: isClosed ? 'var(--bg-2)' : 'transparent' }}>{isClosed ? 'Chiuso' : 'Libero'}</span>
                          </div>
                        ) : (
                          <div draggable={!readOnly}
                            onDragStart={readOnly ? undefined : (e => { e.stopPropagation(); setDrag({ fromEmp: emp.id, fromDay: dayIdx, kind, value: kind }); })}
                            onDragEnd={readOnly ? undefined : (() => { setDrag(null); setHoverCell(null); })}
                            className={`tu-shift ${shiftCellClass(kind, currentStore, dayIdx)}`}
                            style={{ cursor: readOnly ? 'default' : 'grab', minHeight: 36, display: 'flex', alignItems: 'center', justifyContent: 'center', textAlign: 'center', fontSize: 11.5, lineHeight: 1.2, fontWeight: 800, padding: '6px 8px', borderRadius: 10 }}>
                            <span>{normalized.status === 'ferie' ? 'Ferie' : label}</span>
                          </div>
                        )}
                        {isPicker && !readOnly && (
                          <div style={{ position: 'absolute', top: 'calc(100% + 4px)', left: 8, right: 8, minWidth: 220, zIndex: 10, background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 12, padding: 8, boxShadow: 'var(--shadow-lg)', display: 'flex', flexDirection: 'column', gap: 6 }}
                            onClick={e => e.stopPropagation()}>
                            {shiftOptionsForDay(currentStore, dayIdx).map(([k, vv]) => (
                              <button key={k} onClick={() => { ctx.updateShift(emp.id, dayIdx, TU_STATUS_KINDS[k] ? k : makeWorkShift(currentStore, dayIdx, k, ctx.currentStoreId)); setPickerCell(null); }}
                                style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '6px 8px', border: 0, background: 'transparent', borderRadius: 8, textAlign: 'left', fontSize: 12, fontWeight: 600, color: 'var(--ink-2)', cursor: 'pointer' }}>
                                <span style={{ width: 10, height: 10, borderRadius: 3, background: `var(--shift-${k}-bg, var(--shift-${k}))` }}/>
                                <span style={{ flex: 1 }}>{vv.label}</span>
                                <span style={{ color: 'var(--ink-4)', fontSize: 11 }}>{vv.start ? `${vv.start}-${vv.end}` : ''}</span>
                              </button>
                            ))}
                            {normalized.blocks.length > 0 && (
                              <div style={{ borderTop: '1px solid var(--line)', paddingTop: 6, display: 'flex', flexDirection: 'column', gap: 6 }}>
                                <div className="tu-tiny">Negozio per fascia</div>
                                {normalized.blocks.map((b, bi) => (
                                  <div key={bi} style={{ display: 'grid', gridTemplateColumns: '64px 1fr', gap: 6, alignItems: 'center' }}>
                                    <div style={{ fontSize: 11, color: 'var(--ink-3)', fontWeight: 700 }}>{b.start}-{b.end}</div>
                                    <select className="tu-input" value={b.storeId || ctx.currentStoreId} onChange={e => {
                                      const next = { status: 'work', blocks: normalized.blocks.map((x, i) => i === bi ? { ...x, storeId: e.target.value } : x) };
                                      ctx.updateShift(emp.id, dayIdx, next);
                                    }} style={{ height: 30, fontSize: 11, padding: '0 8px' }}>
                                      {assignableStoresForEmployee(emp).map(s => <option key={s.id} value={s.id}>{s.short || s.name}</option>)}
                                    </select>
                                  </div>
                                ))}
                              </div>
                            )}
                          </div>
                        )}
                      </div>
                    );
                  })}
                  <div style={{ padding: '10px 10px', borderLeft: '1px solid var(--line)', borderBottom: '1px solid var(--line)', minHeight: 54, textAlign: 'right', display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
                    <div style={{ fontSize: 11, fontWeight: 800, color: over ? 'var(--danger)' : '#222' }}>{total}h</div>
                    <div style={{ fontSize: 9, color: '#777' }}>/{emp.hours}</div>
                  </div>
                </div>
              );
            })}
          </div>

          {/* Footer totals */}
          {currentTeam.length > 0 && (
            <div style={{ display: 'grid', gridTemplateColumns: '210px repeat(7, minmax(118px, 1fr)) 76px', background: 'var(--surface)', border: '1px solid var(--line)', borderTop: 0, borderRadius: '0 0 14px 14px', overflow: 'hidden', position: 'sticky', bottom: 0, zIndex: 1, minWidth: 1020, boxShadow: '0 -10px 24px rgba(31,27,23,.06)' }}>
              <div style={{ padding: '6px 8px', fontSize: 11, fontWeight: 800, color: '#222' }}>Totale ore</div>
              {TU_DAYS_SHORT.map((_, i) => {
                const tot = currentTeam.reduce((s, e) => s + shiftCellHours((ctx.schedule[e.id] || [])[i] || 'off', currentStore, i, ctx.currentStoreId), 0);
                const exp = expectedHoursForDay(currentStore, i);
                const gap = exp - tot;
                return (
                  <div key={i} style={{ padding: '8px 10px', borderLeft: '1px solid var(--line)', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 4 }}>
                    <div style={{ fontSize: 11, fontWeight: 800, color: gap > 0 ? 'var(--danger)' : '#222' }}>{tot}h</div>
                    <div style={{ fontSize: 9, color: gap > 0 ? 'var(--danger)' : '#777' }}>{exp ? (gap > 0 ? `${gap}h` : 'ok') : 'chiuso'}</div>
                  </div>
                );
              })}
              <div style={{ borderLeft: '1px solid var(--line)', padding: '8px 10px', display: 'flex', flexDirection: 'column', alignItems: 'flex-end', justifyContent: 'center' }}>
                <div style={{ fontSize: 11, fontWeight: 800 }}>
                  {currentTeam.reduce((s, e) => s + totalHoursFor(e), 0)}h
                </div>
                <div style={{ fontSize: 9, color: '#777' }}>totale</div>
              </div>
            </div>
          )}
        </div>
      </div>
      </div>
    </>
  );
}

//  Team (with Add / Remove employee) 
function DesktopTeam({ user }) {
  const ctx = useTurni();
  const currentTeam = ctx.currentTeam;
  const readOnly = !ctx.canEditStore(user, ctx.currentStoreId);
  const companyOptions = ctx.companies.filter(c => ctx.visibleCompanyIds(user).includes(c.id));
  const defaultCompanyId = ctx.currentStore?.companyId || companyOptions[0]?.id || '';
  const companyName = (companyId) => ctx.companies.find(c => c.id === companyId)?.name || 'Societa non indicata';
  const storeName = (storeId) => ctx.stores.find(s => s.id === storeId)?.name || 'Negozio non indicato';
  const storeOptionsForCompany = (companyId) => ctx.stores.filter(s => s.companyId === companyId && ctx.editableStoreIds(user).includes(s.id));
  const storeOptionsForEmployee = (emp) => {
    const companyId = emp.companyId || ctx.stores.find(s => s.id === emp.storeId)?.companyId || defaultCompanyId;
    return storeOptionsForCompany(companyId);
  };
  const defaultStoreId = storeOptionsForCompany(defaultCompanyId)[0]?.id || ctx.currentStoreId || '';
  const [showAdd, setShowAdd] = useState(false);
  const [form, setForm] = useState({ nome: '', cognome: '', hours: '', email: '', companyId: defaultCompanyId, storeId: defaultStoreId });
  const [confirmRemove, setConfirmRemove] = useState(null);
  const [editForm, setEditForm] = useState(null); // { id, nome, cognome, hours, email, companyId, storeId }
  const [moveForm, setMoveForm] = useState(null); // { employee, storeId }

  const handleAdd = () => {
    if (!form.nome.trim() || !form.cognome.trim() || !form.hours) return;
    ctx.addEmployee(form.nome, form.cognome, form.hours, form.email, form.companyId || defaultCompanyId, form.storeId || defaultStoreId);
    setForm({ nome: '', cognome: '', hours: '', email: '', companyId: defaultCompanyId, storeId: defaultStoreId });
    setShowAdd(false);
  };

  const openEdit = (m) => {
    const [nome, ...rest] = (m.name || '').split(' ');
    const storeCompanyId = ctx.stores.find(s => s.id === m.storeId)?.companyId;
    setEditForm({ id: m.id, nome: nome || '', cognome: rest.join(' '), hours: String(m.hours || ''), email: m.email || '', companyId: m.companyId || storeCompanyId || defaultCompanyId, storeId: m.storeId || defaultStoreId });
  };
  const openMove = (m) => {
    const options = storeOptionsForEmployee(m);
    setMoveForm({ employee: m, storeId: m.storeId || options[0]?.id || defaultStoreId });
  };

  const handleEditSave = () => {
    if (!editForm.nome.trim() || !editForm.cognome.trim() || !editForm.hours) return;
    const h = parseInt(editForm.hours, 10) || 0;
    ctx.updateEmployee(editForm.id, {
      name: `${editForm.nome.trim()} ${editForm.cognome.trim()}`,
      hours: h,
      contract: h >= 38 ? `CTI ${h}h` : `PT ${h}h`,
      email: (editForm.email || '').trim().toLowerCase(),
      companyId: editForm.companyId || defaultCompanyId,
      storeId: editForm.storeId || defaultStoreId,
    });
    setEditForm(null);
  };
  const handleMoveSave = () => {
    if (!moveForm?.employee || !moveForm.storeId) return;
    const emp = moveForm.employee;
    const nextStore = ctx.stores.find(s => s.id === moveForm.storeId);
    ctx.updateEmployee(emp.id, {
      storeId: moveForm.storeId,
      companyId: emp.companyId || nextStore?.companyId || defaultCompanyId,
    });
    if (ctx.currentStoreId !== moveForm.storeId) ctx.setCurrentStoreId(moveForm.storeId);
    setMoveForm(null);
  };

  return (
    <>
      <DesktopTopbar
        title="Personale"
        subtitle={`${ctx.currentStore?.name} · ${currentTeam.length} addetti`}
        actions={
          readOnly ? (
            <span className="tu-chip">Sola lettura</span>
          ) : (
            <button className="tu-btn tu-btn-primary" onClick={() => { setForm({ nome: '', cognome: '', hours: '', email: '', companyId: defaultCompanyId, storeId: defaultStoreId }); setShowAdd(true); }}>
              <TuIcon.plus size={16}/> Aggiungi addetto
            </button>
          )
        }
      />

      {/* Add Employee Modal */}
      {showAdd && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 100, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(31,27,23,.45)', backdropFilter: 'blur(6px)' }}
          onClick={() => setShowAdd(false)}>
          <div style={{ width: 520, background: 'var(--surface)', borderRadius: 24, padding: 32, boxShadow: '0 40px 80px rgba(0,0,0,.25)' }}
            onClick={e => e.stopPropagation()}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 24 }}>
              <div className="tu-h2">Nuovo addetto</div>
              <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{ctx.currentStore?.name}</div>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 14 }}>
              <div>
                <label className="tu-label">Nome *</label>
                <input className="tu-input" placeholder="es. Giulia" value={form.nome} onChange={e => setForm(f => ({ ...f, nome: e.target.value }))}/>
              </div>
              <div>
                <label className="tu-label">Cognome *</label>
                <input className="tu-input" placeholder="es. Romano" value={form.cognome} onChange={e => setForm(f => ({ ...f, cognome: e.target.value }))}/>
              </div>
            </div>
            <div style={{ marginBottom: 14 }}>
              <label className="tu-label">Societa assunzione *</label>
              <select className="tu-input" value={form.companyId || defaultCompanyId} onChange={e => {
                const companyId = e.target.value;
                const stores = storeOptionsForCompany(companyId);
                setForm(f => ({ ...f, companyId, storeId: stores.some(s => s.id === f.storeId) ? f.storeId : (stores[0]?.id || '') }));
              }}>
                {companyOptions.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
              </select>
            </div>
            <div style={{ marginBottom: 14 }}>
              <label className="tu-label">Negozio assegnato *</label>
              <select className="tu-input" value={form.storeId || defaultStoreId} onChange={e => setForm(f => ({ ...f, storeId: e.target.value }))}>
                {storeOptionsForCompany(form.companyId || defaultCompanyId).map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
              </select>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 24 }}>
              <div>
                <label className="tu-label">Ore settimanali *</label>
                <input className="tu-input" type="number" min="1" max="48" placeholder="es. 38" value={form.hours} onChange={e => setForm(f => ({ ...f, hours: e.target.value }))}/>
              </div>
              <div>
                <label className="tu-label">Email (OTP)</label>
                <input className="tu-input" type="email" placeholder="es. nome@azienda.it" value={form.email} onChange={e => setForm(f => ({ ...f, email: e.target.value }))}/>
              </div>
            </div>
            {form.nome && form.cognome && form.hours && (
              <div style={{ padding: '10px 14px', background: 'var(--primary-soft)', borderRadius: 12, marginBottom: 16, fontSize: 13 }}>
                <strong>{form.nome} {form.cognome}</strong> · {parseInt(form.hours) >= 38 ? `CTI ${form.hours}h` : `PT ${form.hours}h`} · {ctx.currentStore?.name}
              </div>
            )}
            <div style={{ display: 'flex', gap: 10 }}>
              <button className="tu-btn tu-btn-ghost" style={{ flex: 1 }} onClick={() => setShowAdd(false)}>Annulla</button>
              <button className="tu-btn tu-btn-primary" style={{ flex: 2 }} onClick={handleAdd}
                disabled={!form.nome.trim() || !form.cognome.trim() || !form.hours || !(form.storeId || defaultStoreId)}>
                <TuIcon.plus size={16}/> Aggiungi addetto
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Confirm Remove Modal */}
      {confirmRemove && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 100, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(31,27,23,.45)', backdropFilter: 'blur(6px)' }}
          onClick={() => setConfirmRemove(null)}>
          <div style={{ width: 380, background: 'var(--surface)', borderRadius: 20, padding: 28, boxShadow: '0 40px 80px rgba(0,0,0,.25)' }}
            onClick={e => e.stopPropagation()}>
            <div className="tu-h2" style={{ marginBottom: 8 }}>Rimuovi addetto</div>
            <div style={{ fontSize: 14, color: 'var(--ink-3)', marginBottom: 20 }}>
              Sei sicuro di voler rimuovere <strong>{confirmRemove.name}</strong>? Verranno eliminati anche i suoi turni.
            </div>
            <div style={{ display: 'flex', gap: 10 }}>
              <button className="tu-btn tu-btn-ghost" style={{ flex: 1 }} onClick={() => setConfirmRemove(null)}>Annulla</button>
              <button style={{ flex: 1, height: 38, borderRadius: 999, border: 'none', background: 'var(--danger)', color: '#fff', fontWeight: 700, fontSize: 13, cursor: 'pointer' }}
                onClick={() => { ctx.removeEmployee(confirmRemove.id); setConfirmRemove(null); }}>
                Si, rimuovi
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Move Employee Modal */}
      {moveForm && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 100, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(31,27,23,.45)', backdropFilter: 'blur(6px)' }}
          onClick={() => setMoveForm(null)}>
          <div style={{ width: 480, background: 'var(--surface)', borderRadius: 22, padding: 28, boxShadow: '0 40px 80px rgba(0,0,0,.25)' }}
            onClick={e => e.stopPropagation()}>
            <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16, marginBottom: 22 }}>
              <div>
                <div className="tu-h2">Sposta addetto</div>
                <div style={{ fontSize: 13, color: 'var(--ink-3)', marginTop: 4 }}>
                  {moveForm.employee.name} resta nella stessa societa, cambi solo il negozio assegnato.
                </div>
              </div>
              <button onClick={() => setMoveForm(null)} title="Chiudi"
                style={{ width: 32, height: 32, border: '1px solid var(--line)', background: 'var(--surface)', borderRadius: 8, color: 'var(--ink-2)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}>
                <TuIcon.x size={14}/>
              </button>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 16 }}>
              <div style={{ border: '1px solid var(--line)', background: 'var(--bg)', borderRadius: 12, padding: 12 }}>
                <div className="tu-tiny">Da</div>
                <div style={{ fontSize: 14, fontWeight: 850, marginTop: 4 }}>{storeName(moveForm.employee.storeId)}</div>
              </div>
              <div style={{ border: '1px solid var(--line)', background: 'var(--bg)', borderRadius: 12, padding: 12 }}>
                <div className="tu-tiny">Societa</div>
                <div style={{ fontSize: 14, fontWeight: 850, marginTop: 4 }}>
                  {companyName(moveForm.employee.companyId || ctx.stores.find(s => s.id === moveForm.employee.storeId)?.companyId)}
                </div>
              </div>
            </div>
            <div style={{ marginBottom: 18 }}>
              <label className="tu-label">Nuovo negozio *</label>
              <select className="tu-input" value={moveForm.storeId} onChange={e => setMoveForm(f => ({ ...f, storeId: e.target.value }))}>
                {storeOptionsForEmployee(moveForm.employee).map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
              </select>
            </div>
            <div style={{ padding: '10px 12px', background: 'var(--primary-soft)', borderRadius: 12, marginBottom: 18, fontSize: 12.5, color: 'var(--primary-deep)', fontWeight: 750 }}>
              Dopo il salvataggio lo vedrai nella lista del negozio scelto.
            </div>
            <div style={{ display: 'flex', gap: 10 }}>
              <button className="tu-btn tu-btn-ghost" style={{ flex: 1 }} onClick={() => setMoveForm(null)}>Annulla</button>
              <button className="tu-btn tu-btn-primary" style={{ flex: 1.6 }} onClick={handleMoveSave} disabled={!moveForm.storeId || moveForm.storeId === moveForm.employee.storeId}>
                <TuIcon.swap size={16}/> Sposta
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Edit Employee Modal */}
      {editForm && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 100, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(31,27,23,.45)', backdropFilter: 'blur(6px)' }}
          onClick={() => setEditForm(null)}>
          <div style={{ width: 520, background: 'var(--surface)', borderRadius: 24, padding: 32, boxShadow: '0 40px 80px rgba(0,0,0,.25)' }}
            onClick={e => e.stopPropagation()}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 24 }}>
              <div className="tu-h2">Modifica addetto</div>
              <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{ctx.currentStore?.name}</div>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 14 }}>
              <div>
                <label className="tu-label">Nome *</label>
                <input className="tu-input" value={editForm.nome} onChange={e => setEditForm(f => ({ ...f, nome: e.target.value }))}/>
              </div>
              <div>
                <label className="tu-label">Cognome *</label>
                <input className="tu-input" value={editForm.cognome} onChange={e => setEditForm(f => ({ ...f, cognome: e.target.value }))}/>
              </div>
            </div>
            <div style={{ marginBottom: 14 }}>
              <label className="tu-label">Societa assunzione *</label>
              <select className="tu-input" value={editForm.companyId || defaultCompanyId} onChange={e => {
                const companyId = e.target.value;
                const stores = storeOptionsForCompany(companyId);
                setEditForm(f => ({ ...f, companyId, storeId: stores.some(s => s.id === f.storeId) ? f.storeId : (stores[0]?.id || '') }));
              }}>
                {companyOptions.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
              </select>
            </div>
            <div style={{ marginBottom: 14 }}>
              <label className="tu-label">Negozio assegnato *</label>
              <select className="tu-input" value={editForm.storeId || defaultStoreId} onChange={e => setEditForm(f => ({ ...f, storeId: e.target.value }))}>
                {storeOptionsForCompany(editForm.companyId || defaultCompanyId).map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
              </select>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 24 }}>
              <div>
                <label className="tu-label">Ore settimanali *</label>
                <input className="tu-input" type="number" min="1" max="48" value={editForm.hours} onChange={e => setEditForm(f => ({ ...f, hours: e.target.value }))}/>
              </div>
              <div>
                <label className="tu-label">Email (OTP)</label>
                <input className="tu-input" type="email" placeholder="es. nome@azienda.it" value={editForm.email} onChange={e => setEditForm(f => ({ ...f, email: e.target.value }))}/>
              </div>
            </div>
            {editForm.nome && editForm.cognome && editForm.hours && (
              <div style={{ padding: '10px 14px', background: 'var(--primary-soft)', borderRadius: 12, marginBottom: 16, fontSize: 13 }}>
                <strong>{editForm.nome} {editForm.cognome}</strong> · {parseInt(editForm.hours) >= 38 ? `CTI ${editForm.hours}h` : `PT ${editForm.hours}h`} · {ctx.currentStore?.name}
              </div>
            )}
            <div style={{ marginBottom: 16, padding: '12px 14px', background: 'var(--bg)', border: '1px solid var(--line)', borderRadius: 12 }}>
              <div className="tu-label" style={{ marginBottom: 4 }}>Accesso via OTP</div>
              <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>Il codice OTP verrà inviato all'indirizzo email indicato sopra.</div>
              <div style={{ fontSize: 11, color: 'var(--ink-4)', marginTop: 6 }}>L'addetto riceverà i codici di accesso via email all'indirizzo indicato sopra.</div>
            </div>
            <div style={{ display: 'flex', gap: 10 }}>
              <button className="tu-btn tu-btn-ghost" style={{ flex: 1 }} onClick={() => setEditForm(null)}>Annulla</button>
              <button className="tu-btn tu-btn-primary" style={{ flex: 2 }} onClick={handleEditSave}
                disabled={!editForm.nome.trim() || !editForm.cognome.trim() || !editForm.hours || !(editForm.storeId || defaultStoreId)}>
                <TuIcon.check size={16}/> Salva modifiche
              </button>
            </div>
          </div>
        </div>
      )}

      <div style={{ flex: 1, overflow: 'auto', padding: 28 }}>
        <div className="tu-card" style={{ padding: 0, overflow: 'hidden' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '2fr 1.35fr 1fr 1fr 1fr 168px', padding: '14px 22px', borderBottom: '1px solid var(--line)', fontSize: 11.5, color: 'var(--ink-3)', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.04em' }}>
            <div>Nome</div><div>Societa assunzione</div><div>Contratto</div><div>Email (OTP)</div><div>Turni questa sett.</div><div></div>
          </div>
          {currentTeam.length === 0 && (
            <div style={{ padding: 48, textAlign: 'center', color: 'var(--ink-3)' }}>
              Nessun addetto in questo store. Usa "Aggiungi addetto" per iniziare.
            </div>
          )}
          {currentTeam.map((m, i) => {
            const weekShifts = (ctx.schedule[m.id] || []).filter(k => k !== 'off' && k !== 'ferie').length;
            return (
              <div key={m.id} style={{ display: 'grid', gridTemplateColumns: '2fr 1.35fr 1fr 1fr 1fr 168px', padding: '14px 22px', borderBottom: i < currentTeam.length - 1 ? '1px solid var(--line)' : 0, alignItems: 'center', fontSize: 13.5 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                  <TuAvatar name={m.name} size={34}/>
                  <div style={{ lineHeight: 1.2 }}>
                    <div style={{ fontWeight: 700 }}>{m.name}</div>
                    <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{m.role}</div>
                  </div>
                </div>
                <div style={{ fontSize: 12.5, color: 'var(--ink-2)', fontWeight: 650, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                  {companyName(m.companyId || ctx.stores.find(s => s.id === m.storeId)?.companyId)}
                </div>
                <div style={{ fontWeight: 600 }}>{m.contract}</div>
                <div style={{ fontSize: 12, color: m.email ? 'var(--ink-2)' : 'var(--ink-4)' }}>
                  {m.email || ''}
                </div>
                <div>
                  <span className={`tu-chip ${weekShifts >= 5 ? 'tu-chip-ok' : weekShifts > 0 ? 'tu-chip-warn' : ''}`}>
                    {weekShifts} turni
                  </span>
                </div>
                <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
                  {readOnly ? (
                    <span style={{ fontSize: 11, color: 'var(--ink-4)' }}></span>
                  ) : (
                    <>
                      <button onClick={() => openMove(m)} title="Sposta in un altro negozio"
                        style={{ height: 32, border: '1px solid var(--line)', background: 'var(--surface)', borderRadius: 8, color: 'var(--primary-deep)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6, padding: '0 10px', cursor: 'pointer', fontSize: 12, fontWeight: 800 }}>
                        <TuIcon.swap size={14}/> Sposta
                      </button>
                      <button onClick={() => openEdit(m)} title="Modifica"
                        style={{ width: 32, height: 32, border: '1px solid var(--line)', background: 'var(--surface)', borderRadius: 8, color: 'var(--ink-2)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}>
                        <TuIcon.edit size={14}/>
                      </button>
                      <button onClick={() => setConfirmRemove(m)} title="Rimuovi"
                        style={{ width: 32, height: 32, border: '1px solid var(--line)', background: 'var(--surface)', borderRadius: 8, color: 'var(--danger)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}>
                        <TuIcon.trash size={14}/>
                      </button>
                    </>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </>
  );
}

//  Structure (Società & Negozi) 
const STORE_DAY_KEYS = ['mon','tue','wed','thu','fri','sat','sun'];
const STORE_DAY_LABELS = ['Lun','Mar','Mer','Gio','Ven','Sab','Dom'];
function cloneHours(hours) {
  const fallback = window.DEFAULT_OPENING_HOURS || {
    mon: [], tue: [], wed: [], thu: [], fri: [], sat: [], sun: [],
  };
  return JSON.parse(JSON.stringify(hours || fallback));
}
function formatStoreHours(hours) {
  const days = STORE_DAY_KEYS.map((key, i) => {
    const blocks = hours?.[key] || [];
    return `${STORE_DAY_LABELS[i]} ${blocks.length ? blocks.map(b => `${b.start}-${b.end}`).join(' / ') : 'chiuso'}`;
  });
  return days.join(' · ');
}
function storeTypeLabel(type) {
  return type === 'mall' ? 'Centro commerciale' : 'Strada';
}
function StoreHoursEditor({ form, target, setTypePreset, updateBlock, addBlock, removeBlock }) {
  return (
    <div style={{ border: '1px solid var(--line)', borderRadius: 14, padding: 14, background: 'var(--bg)', marginBottom: 16 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, marginBottom: 12 }}>
        <div>
          <div className="tu-label" style={{ marginBottom: 2 }}>Tipo e orari negozio</div>
          <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>Il tipo imposta solo un preset: gli orari restano modificabili.</div>
        </div>
        <div className="tu-seg">
          <button className={form.type !== 'mall' ? 'is-active' : ''} onClick={() => setTypePreset('street', target)}>Strada</button>
          <button className={form.type === 'mall' ? 'is-active' : ''} onClick={() => setTypePreset('mall', target)}>Centro</button>
        </div>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {STORE_DAY_KEYS.map((day, di) => (
          <div key={day} style={{ display: 'grid', gridTemplateColumns: '42px 1fr auto', gap: 8, alignItems: 'start' }}>
            <div style={{ fontSize: 12, fontWeight: 800, color: 'var(--ink-3)', paddingTop: 8 }}>{STORE_DAY_LABELS[di]}</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              {(form.openingHours?.[day] || []).map((block, bi) => (
                <div key={bi} style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
                  <input className="tu-input" type="time" value={block.start} onChange={e => updateBlock(target, day, bi, 'start', e.target.value)} style={{ height: 34, fontSize: 12 }}/>
                  <span style={{ color: 'var(--ink-3)', fontSize: 12 }}>-</span>
                  <input className="tu-input" type="time" value={block.end} onChange={e => updateBlock(target, day, bi, 'end', e.target.value)} style={{ height: 34, fontSize: 12 }}/>
                  <button onClick={() => removeBlock(target, day, bi)} title="Rimuovi fascia" style={{ width: 30, height: 30, borderRadius: 8, border: '1px solid var(--line)', background: 'var(--surface)', color: 'var(--danger)', cursor: 'pointer' }}><TuIcon.x size={13}/></button>
                </div>
              ))}
              {(form.openingHours?.[day] || []).length === 0 && <div style={{ fontSize: 12, color: 'var(--ink-4)', paddingTop: 8 }}>Chiuso</div>}
            </div>
            <button className="tu-btn tu-btn-ghost" style={{ height: 30, fontSize: 12, padding: '0 10px' }} onClick={() => addBlock(target, day)}>+ fascia</button>
          </div>
        ))}
      </div>
    </div>
  );
}
function DesktopStructure({ user }) {
  const ctx = useTurni();
  const canManage = ctx.canManageStructure(user);          // admin o capo (gestione negozi)
  const canBrands = ctx.canManageBrandsAndCompanies(user); // solo admin (crea/elimina Società)
  const brandIds  = ctx.visibleBrandIds(user);
  const visibleStores = ctx.visibleStoreIds(user);
  const visibleCompanies = ctx.visibleCompanyIds(user);
  const brands = ctx.brands.filter(b => brandIds.includes(b.id));

  const [showAddBrand, setShowAddBrand] = useState(false);
  const [newBrandName, setNewBrandName] = useState('');
  const [confirmRemoveBrand, setConfirmRemoveBrand] = useState(null);
  const [showAddCompany, setShowAddCompany] = useState(null); // brandId
  const [newCompanyName, setNewCompanyName] = useState('');
  const [showAddStore, setShowAddStore] = useState(null); // companyId
  const [storeForm, setStoreForm] = useState({ name: '', city: '', short: '', type: 'street', openingHours: cloneHours(ctx.defaultOpeningHours('street')) });
  const [editStore, setEditStore] = useState(null);
  const [confirmRemoveCompany, setConfirmRemoveCompany] = useState(null);
  const [confirmRemoveStore, setConfirmRemoveStore] = useState(null);

  const handleAddBrand = () => {
    if (!newBrandName.trim()) return;
    ctx.addBrand(newBrandName);
    setNewBrandName(''); setShowAddBrand(false);
  };
  const handleAddCompany = () => {
    if (!newCompanyName.trim()) return;
    ctx.addCompany(newCompanyName, showAddCompany);
    setNewCompanyName(''); setShowAddCompany(null);
  };
  const handleAddStore = () => {
    if (!storeForm.name.trim() || !storeForm.city.trim()) return;
    ctx.addStore(showAddStore, storeForm.name, storeForm.city, storeForm.short, storeForm.type, storeForm.openingHours);
    setStoreForm({ name: '', city: '', short: '', type: 'street', openingHours: cloneHours(ctx.defaultOpeningHours('street')) }); setShowAddStore(null);
  };
  const openStoreEditor = (store) => {
    setEditStore({ ...store, type: store.type || 'street', openingHours: cloneHours(store.openingHours || ctx.defaultOpeningHours(store.type || 'street')) });
  };
  const setStoreTypePreset = (type, target = 'add') => {
    const next = { type, openingHours: cloneHours(ctx.defaultOpeningHours(type)) };
    if (target === 'edit') setEditStore(s => ({ ...s, ...next }));
    else setStoreForm(f => ({ ...f, ...next }));
  };
  const updateHoursBlock = (target, day, idx, field, value) => {
    const setter = target === 'edit' ? setEditStore : setStoreForm;
    setter(form => {
      const openingHours = cloneHours(form.openingHours);
      openingHours[day][idx][field] = value;
      return { ...form, openingHours };
    });
  };
  const addHoursBlock = (target, day) => {
    const setter = target === 'edit' ? setEditStore : setStoreForm;
    setter(form => {
      const openingHours = cloneHours(form.openingHours);
      openingHours[day] = [...(openingHours[day] || []), { start: '09:00', end: '13:00' }];
      return { ...form, openingHours };
    });
  };
  const removeHoursBlock = (target, day, idx) => {
    const setter = target === 'edit' ? setEditStore : setStoreForm;
    setter(form => {
      const openingHours = cloneHours(form.openingHours);
      openingHours[day] = (openingHours[day] || []).filter((_, i) => i !== idx);
      return { ...form, openingHours };
    });
  };
  const handleEditStore = () => {
    if (!editStore?.name?.trim() || !editStore?.city?.trim()) return;
    ctx.updateStore(editStore.id, {
      name: editStore.name,
      city: editStore.city,
      short: editStore.short,
      type: editStore.type,
      openingHours: editStore.openingHours,
    });
    setEditStore(null);
  };

  return (
    <>
      <DesktopTopbar
        title="Società & Negozi"
        subtitle={`${ctx.holding} · ${canManage ? 'Struttura del gruppo' : 'Sola lettura'}`}
        actions={canBrands && (
          <button className="tu-btn tu-btn-primary" onClick={() => setShowAddBrand(true)}>
            <TuIcon.plus size={16}/> Nuovo brand
          </button>
        )}
      />

      {/* Add Brand Modal */}
      {showAddBrand && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 100, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(31,27,23,.45)', backdropFilter: 'blur(6px)' }}
          onClick={() => setShowAddBrand(false)}>
          <div style={{ width: 400, background: 'var(--surface)', borderRadius: 20, padding: 28, boxShadow: '0 40px 80px rgba(0,0,0,.25)' }} onClick={e => e.stopPropagation()}>
            <div className="tu-h2" style={{ marginBottom: 4 }}>Nuovo brand</div>
            <div style={{ fontSize: 13, color: 'var(--ink-3)', marginBottom: 20 }}>Sotto la holding {ctx.holding}</div>
            <label className="tu-label">Nome brand *</label>
            <input className="tu-input" placeholder="es. Maori Beauty" value={newBrandName} onChange={e => setNewBrandName(e.target.value)} style={{ marginBottom: 20 }} autoFocus
              onKeyDown={e => e.key === 'Enter' && handleAddBrand()}/>
            <div style={{ display: 'flex', gap: 10 }}>
              <button className="tu-btn tu-btn-ghost" style={{ flex: 1 }} onClick={() => setShowAddBrand(false)}>Annulla</button>
              <button className="tu-btn tu-btn-primary" style={{ flex: 2 }} onClick={handleAddBrand}>Crea brand</button>
            </div>
          </div>
        </div>
      )}

      {/* Confirm Remove Brand */}
      {confirmRemoveBrand && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 100, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(31,27,23,.45)', backdropFilter: 'blur(6px)' }}
          onClick={() => setConfirmRemoveBrand(null)}>
          <div style={{ width: 410, background: 'var(--surface)', borderRadius: 20, padding: 28, boxShadow: '0 40px 80px rgba(0,0,0,.25)' }} onClick={e => e.stopPropagation()}>
            <div className="tu-h2" style={{ marginBottom: 8 }}>Elimina brand</div>
            <div style={{ fontSize: 14, color: 'var(--ink-3)', marginBottom: 20 }}>
              Eliminando <strong>{confirmRemoveBrand.name}</strong> verranno eliminate tutte le sue Società, negozi e addetti.
            </div>
            <div style={{ display: 'flex', gap: 10 }}>
              <button className="tu-btn tu-btn-ghost" style={{ flex: 1 }} onClick={() => setConfirmRemoveBrand(null)}>Annulla</button>
              <button style={{ flex: 1, height: 38, borderRadius: 999, border: 'none', background: 'var(--danger)', color: '#fff', fontWeight: 700, fontSize: 13, cursor: 'pointer' }}
                onClick={() => { ctx.removeBrand(confirmRemoveBrand.id); setConfirmRemoveBrand(null); }}>
                Si, elimina
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Add Company Modal */}
      {showAddCompany && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 100, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(31,27,23,.45)', backdropFilter: 'blur(6px)' }}
          onClick={() => setShowAddCompany(null)}>
          <div style={{ width: 400, background: 'var(--surface)', borderRadius: 20, padding: 28, boxShadow: '0 40px 80px rgba(0,0,0,.25)' }} onClick={e => e.stopPropagation()}>
            <div className="tu-h2" style={{ marginBottom: 4 }}>Nuova Società</div>
            <div style={{ fontSize: 13, color: 'var(--ink-3)', marginBottom: 20 }}>{ctx.brands.find(b => b.id === showAddCompany)?.name}</div>
            <label className="tu-label">Nome Società *</label>
            <input className="tu-input" placeholder="es. Sud Italia Retail S.r.l." value={newCompanyName} onChange={e => setNewCompanyName(e.target.value)} style={{ marginBottom: 20 }}/>
            <div style={{ display: 'flex', gap: 10 }}>
              <button className="tu-btn tu-btn-ghost" style={{ flex: 1 }} onClick={() => setShowAddCompany(null)}>Annulla</button>
              <button className="tu-btn tu-btn-primary" style={{ flex: 2 }} onClick={handleAddCompany}>Crea Società</button>
            </div>
          </div>
        </div>
      )}

      {/* Add Store Modal */}
      {showAddStore && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 100, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(31,27,23,.45)', backdropFilter: 'blur(6px)' }}
          onClick={() => setShowAddStore(null)}>
          <div style={{ width: 720, maxHeight: '88vh', overflow: 'auto', background: 'var(--surface)', borderRadius: 20, padding: 28, boxShadow: '0 40px 80px rgba(0,0,0,.25)' }} onClick={e => e.stopPropagation()}>
            <div className="tu-h2" style={{ marginBottom: 4 }}>Nuovo negozio</div>
            <div style={{ fontSize: 13, color: 'var(--ink-3)', marginBottom: 20 }}>{ctx.companies.find(c => c.id === showAddStore)?.name}</div>
            <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 12, marginBottom: 12 }}>
              <div>
                <label className="tu-label">Nome negozio *</label>
                <input className="tu-input" placeholder="es. Napoli · Toledo" value={storeForm.name} onChange={e => setStoreForm(f => ({ ...f, name: e.target.value }))}/>
              </div>
              <div>
                <label className="tu-label">Codice breve</label>
                <input className="tu-input" placeholder="NA-TOL" value={storeForm.short} onChange={e => setStoreForm(f => ({ ...f, short: e.target.value }))}/>
              </div>
            </div>
            <div style={{ marginBottom: 20 }}>
              <label className="tu-label">Città *</label>
              <input className="tu-input" placeholder="es. Napoli" value={storeForm.city} onChange={e => setStoreForm(f => ({ ...f, city: e.target.value }))}/>
            </div>
            <StoreHoursEditor form={storeForm} target="add" setTypePreset={setStoreTypePreset} updateBlock={updateHoursBlock} addBlock={addHoursBlock} removeBlock={removeHoursBlock}/>
            <div style={{ display: 'flex', gap: 10 }}>
              <button className="tu-btn tu-btn-ghost" style={{ flex: 1 }} onClick={() => setShowAddStore(null)}>Annulla</button>
              <button className="tu-btn tu-btn-primary" style={{ flex: 2 }} onClick={handleAddStore}>Aggiungi negozio</button>
            </div>
          </div>
        </div>
      )}

      {/* Edit Store Modal */}
      {editStore && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 100, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(31,27,23,.45)', backdropFilter: 'blur(6px)' }}
          onClick={() => setEditStore(null)}>
          <div style={{ width: 720, maxHeight: '88vh', overflow: 'auto', background: 'var(--surface)', borderRadius: 20, padding: 28, boxShadow: '0 40px 80px rgba(0,0,0,.25)' }} onClick={e => e.stopPropagation()}>
            <div className="tu-h2" style={{ marginBottom: 4 }}>Modifica negozio</div>
            <div style={{ fontSize: 13, color: 'var(--ink-3)', marginBottom: 20 }}>{ctx.companies.find(c => c.id === editStore.companyId)?.name}</div>
            <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 12, marginBottom: 12 }}>
              <div>
                <label className="tu-label">Nome negozio *</label>
                <input className="tu-input" value={editStore.name} onChange={e => setEditStore(f => ({ ...f, name: e.target.value }))}/>
              </div>
              <div>
                <label className="tu-label">Codice breve</label>
                <input className="tu-input" value={editStore.short || ''} onChange={e => setEditStore(f => ({ ...f, short: e.target.value }))}/>
              </div>
            </div>
            <div style={{ marginBottom: 20 }}>
              <label className="tu-label">Città *</label>
              <input className="tu-input" value={editStore.city} onChange={e => setEditStore(f => ({ ...f, city: e.target.value }))}/>
            </div>
            <StoreHoursEditor form={editStore} target="edit" setTypePreset={setStoreTypePreset} updateBlock={updateHoursBlock} addBlock={addHoursBlock} removeBlock={removeHoursBlock}/>
            <div style={{ display: 'flex', gap: 10 }}>
              <button className="tu-btn tu-btn-ghost" style={{ flex: 1 }} onClick={() => setEditStore(null)}>Annulla</button>
              <button className="tu-btn tu-btn-primary" style={{ flex: 2 }} onClick={handleEditStore}>Salva modifiche</button>
            </div>
          </div>
        </div>
      )}

      {/* Confirm Remove Company */}
      {confirmRemoveCompany && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 100, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(31,27,23,.45)', backdropFilter: 'blur(6px)' }}
          onClick={() => setConfirmRemoveCompany(null)}>
          <div style={{ width: 400, background: 'var(--surface)', borderRadius: 20, padding: 28, boxShadow: '0 40px 80px rgba(0,0,0,.25)' }} onClick={e => e.stopPropagation()}>
            <div className="tu-h2" style={{ marginBottom: 8 }}>Rimuovi Società</div>
            <div style={{ fontSize: 14, color: 'var(--ink-3)', marginBottom: 20 }}>
              Rimuovendo <strong>{confirmRemoveCompany.name}</strong> verranno eliminati tutti i suoi negozi e dipendenti.
            </div>
            <div style={{ display: 'flex', gap: 10 }}>
              <button className="tu-btn tu-btn-ghost" style={{ flex: 1 }} onClick={() => setConfirmRemoveCompany(null)}>Annulla</button>
              <button style={{ flex: 1, height: 38, borderRadius: 999, border: 'none', background: 'var(--danger)', color: '#fff', fontWeight: 700, fontSize: 13, cursor: 'pointer' }}
                onClick={() => { ctx.removeCompany(confirmRemoveCompany.id); setConfirmRemoveCompany(null); }}>
                Si, elimina
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Confirm Remove Store */}
      {confirmRemoveStore && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 100, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(31,27,23,.45)', backdropFilter: 'blur(6px)' }}
          onClick={() => setConfirmRemoveStore(null)}>
          <div style={{ width: 400, background: 'var(--surface)', borderRadius: 20, padding: 28, boxShadow: '0 40px 80px rgba(0,0,0,.25)' }} onClick={e => e.stopPropagation()}>
            <div className="tu-h2" style={{ marginBottom: 8 }}>Rimuovi negozio</div>
            <div style={{ fontSize: 14, color: 'var(--ink-3)', marginBottom: 20 }}>
              Rimuovendo <strong>{confirmRemoveStore.name}</strong> verranno eliminati tutti i suoi dipendenti e turni.
            </div>
            <div style={{ display: 'flex', gap: 10 }}>
              <button className="tu-btn tu-btn-ghost" style={{ flex: 1 }} onClick={() => setConfirmRemoveStore(null)}>Annulla</button>
              <button style={{ flex: 1, height: 38, borderRadius: 999, border: 'none', background: 'var(--danger)', color: '#fff', fontWeight: 700, fontSize: 13, cursor: 'pointer' }}
                onClick={() => { ctx.removeStore(confirmRemoveStore.id); setConfirmRemoveStore(null); }}>
                Si, elimina
              </button>
            </div>
          </div>
        </div>
      )}

      <div style={{ flex: 1, overflow: 'auto', padding: 28 }}>
        {/* Holding header */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 18, marginBottom: 24, padding: '16px 24px', background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 18 }}>
          <div style={{ flexShrink: 0 }}><MaoriLogo width={116}/></div>
          <div style={{ flex: 1 }}>
            <div className="tu-tiny">Holding</div>
            <div style={{ fontSize: 13, color: 'var(--ink-3)', marginTop: 4 }}>
              {brands.length} brand · {ctx.companies.filter(c => visibleCompanies.includes(c.id)).length} Società · {ctx.stores.filter(s => visibleStores.includes(s.id)).length} negozi · {ctx.team.filter(e => visibleStores.includes(e.storeId)).length} addetti
            </div>
          </div>
        </div>

        {brands.length === 0 && (
          <div style={{ textAlign: 'center', padding: 60, color: 'var(--ink-3)' }}>Nessun brand visibile.</div>
        )}

        <div style={{ display: 'flex', flexDirection: 'column', gap: 28 }}>
          {brands.map(brand => {
            const brandCompanies = ctx.companies.filter(c => c.brandId === brand.id && visibleCompanies.includes(c.id));
            const brandStores = ctx.stores.filter(s => brandCompanies.find(c => c.id === s.companyId));
            const brandTeam = ctx.team.filter(e => brandStores.find(s => s.id === e.storeId)).length;
            return (
              <div key={brand.id}>
                {/* Brand header */}
                <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 16, padding: '18px 24px', background: 'var(--surface)', borderRadius: 18, border: '1px solid var(--line)' }}>
                  <TuLogoMark size={44}/>
                  <div style={{ flex: 1 }}>
                    <div className="tu-tiny">Brand</div>
                    <div style={{ fontSize: 22, fontWeight: 800, letterSpacing: '-.02em' }}>{brand.name}</div>
                    <div style={{ fontSize: 13, color: 'var(--ink-3)', marginTop: 2 }}>{brandCompanies.length} Società · {brandStores.length} negozi · {brandTeam} addetti</div>
                  </div>
                  {canBrands && (
                    <>
                      <button className="tu-btn tu-btn-primary" style={{ height: 36 }} onClick={() => setShowAddCompany(brand.id)}>
                        <TuIcon.plus size={14}/> Nuova Società
                      </button>
                      <button onClick={() => setConfirmRemoveBrand(brand)} title="Elimina brand"
                        style={{ width: 36, height: 36, border: '1px solid var(--line)', background: 'var(--surface)', borderRadius: 8, color: 'var(--danger)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}>
                        <TuIcon.trash size={15}/>
                      </button>
                    </>
                  )}
                </div>

                {brandCompanies.length === 0 && (
                  <div style={{ textAlign: 'center', padding: 32, color: 'var(--ink-3)' }}>Nessuna Società in questo brand.</div>
                )}

                <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                  {brandCompanies.map(co => {
                    const coStores = ctx.stores.filter(s => s.companyId === co.id && visibleStores.includes(s.id));
                    const coTeamCount = ctx.team.filter(e => coStores.find(s => s.id === e.storeId)).length;
                    return (
                      <div key={co.id} className="tu-card" style={{ padding: 0, overflow: 'hidden' }}>
                        {/* Company header */}
                        <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '16px 22px', borderBottom: '1px solid var(--line)', background: 'var(--bg)' }}>
                          <div style={{ width: 36, height: 36, borderRadius: 10, background: 'var(--primary-soft)', color: 'var(--primary-deep)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800, fontSize: 14 }}>
                            {co.name[0]}
                          </div>
                          <div style={{ flex: 1 }}>
                            <div style={{ fontWeight: 700, fontSize: 15 }}>{co.name}</div>
                            <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{coStores.length} negozi · {coTeamCount} addetti</div>
                          </div>
                          {canManage && (
                            <button className="tu-btn tu-btn-soft" style={{ height: 32, fontSize: 12 }} onClick={() => setShowAddStore(co.id)}>
                              <TuIcon.plus size={14}/> Aggiungi negozio
                            </button>
                          )}
                          {canBrands && (
                            <button onClick={() => setConfirmRemoveCompany(co)} title="Rimuovi Società"
                              style={{ width: 32, height: 32, border: '1px solid var(--line)', background: 'var(--surface)', borderRadius: 8, color: 'var(--danger)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}>
                              <TuIcon.trash size={14}/>
                            </button>
                          )}
                        </div>

                        {/* Stores list */}
                        {coStores.length === 0 && (
                          <div style={{ padding: '20px 22px', color: 'var(--ink-4)', fontSize: 13 }}>Nessun negozio.</div>
                        )}
                        {coStores.map((s, si) => {
                          const storeTeam = ctx.team.filter(e => e.storeId === s.id).length;
                          const isActive = s.id === ctx.currentStoreId;
                          const storeHours = s.openingHours || ctx.defaultOpeningHours(s.type || 'street');
                          return (
                            <div key={s.id} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '14px 22px', borderBottom: si < coStores.length - 1 ? '1px solid var(--line)' : 0, background: isActive ? 'var(--primary-soft)' : 'transparent' }}>
                              <div style={{ width: 32, height: 32, borderRadius: 8, background: isActive ? 'var(--primary)' : 'var(--bg-2)', color: isActive ? '#fff' : 'var(--ink-3)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 10, fontWeight: 800 }}>{s.short?.slice(0,2) || s.name[0]}</div>
                              <div style={{ flex: 1, minWidth: 0 }}>
                                <div style={{ fontWeight: 600, fontSize: 14, color: isActive ? 'var(--primary-deep)' : 'var(--ink)' }}>{s.name}</div>
                                <div style={{ fontSize: 11.5, color: isActive ? 'var(--primary-deep)' : 'var(--ink-3)' }}>{s.city} · {storeTypeLabel(s.type)} · {storeTeam} addetti</div>
                                <div title={formatStoreHours(storeHours)} style={{ marginTop: 3, fontSize: 11, color: isActive ? 'var(--primary-deep)' : 'var(--ink-4)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                                  {formatStoreHours(storeHours)}
                                </div>
                              </div>
                              {isActive && <span className="tu-chip tu-chip-primary" style={{ fontSize: 11 }}>Store attivo</span>}
                              <button onClick={() => ctx.setCurrentStoreId(s.id)} className="tu-btn tu-btn-ghost" style={{ height: 30, fontSize: 12 }}>
                                {isActive ? 'Selezionato' : 'Seleziona'}
                              </button>
                              {canManage && (
                                <>
                                  <button onClick={() => openStoreEditor(s)} title="Modifica negozio e orari"
                                    style={{ width: 30, height: 30, border: '1px solid var(--line)', background: 'var(--surface)', borderRadius: 8, color: 'var(--ink-3)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}>
                                    <TuIcon.edit size={13}/>
                                  </button>
                                  <button onClick={() => setConfirmRemoveStore(s)} title="Rimuovi negozio"
                                    style={{ width: 30, height: 30, border: '1px solid var(--line)', background: 'var(--surface)', borderRadius: 8, color: 'var(--danger)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}>
                                    <TuIcon.trash size={13}/>
                                  </button>
                                </>
                              )}
                            </div>
                          );
                        })}
                      </div>
                    );
                  })}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </>
  );
}

function PlannerMetric({ label, value, tone = 'flat' }) {
  const color = tone === 'warn' ? 'var(--danger)' : tone === 'ok' ? 'var(--ok)' : 'var(--ink)';
  return (
    <div style={{ minHeight: 72, border: '1px solid var(--line)', borderRadius: 8, background: 'var(--bg)', padding: 12, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
      <div style={{ fontSize: 10.5, color: 'var(--ink-3)', fontWeight: 900, textTransform: 'uppercase' }}>{label}</div>
      <div style={{ fontSize: 22, fontWeight: 900, color, marginTop: 3 }}>{value}</div>
    </div>
  );
}

// Override planner: daily-first layout, clearer than the old weekly spreadsheet.
DesktopPlanner = function DesktopPlannerRedesign({ user }) {
  const ctx = useTurni();
  const currentStore = ctx.currentStore;
  const currentCompanyId = currentStore?.companyId || ctx.companies[0]?.id || '';
  const currentCompany = ctx.companies.find(c => c.id === currentCompanyId);
  const storeName = (storeId) => ctx.stores.find(s => s.id === storeId)?.name || 'Negozio non indicato';
  const employeeCompanyId = (emp) => emp.companyId || ctx.stores.find(s => s.id === emp.storeId)?.companyId || currentCompanyId;
  const homeStoreFor = (emp) => ctx.stores.find(s => s.id === emp.storeId) || currentStore;
  const companyTeam = ctx.team.filter(emp => employeeCompanyId(emp) === currentCompanyId);
  const assignableStoresForEmployee = (emp) => {
    const companyId = employeeCompanyId(emp);
    return ctx.stores.filter(s => s.companyId === companyId && ctx.editableStoreIds(user).includes(s.id));
  };
  const readOnly = !ctx.canEditStore(user, ctx.currentStoreId);
  const [selectedDay, setSelectedDay] = useState(0);
  const [dragKind, setDragKind] = useState(null);
  const [hoverEmpId, setHoverEmpId] = useState(null);
  const [confirmMsg, setConfirmMsg] = useState('');
  const handleConfirmWeek = async () => {
    const r = await ctx.confirmWeek?.(ctx.currentStoreId).catch(() => null);
    const n = r?.notified ?? 0;
    setConfirmMsg(n > 0 ? `Notificati ${n} addetti` : 'Nessuna push (Web Push non attivo o nessun addetto)');
    setTimeout(() => setConfirmMsg(''), 4000);
  };

  const openFor = (dayIdx) => currentStore ? openingBlocksFor(currentStore, dayIdx) : [];
  const expectedFor = (dayIdx) => currentStore ? expectedHoursForDay(currentStore, dayIdx) : 0;
  const dayOpenBlocks = openFor(selectedDay);
  const shiftOptions = currentStore ? shiftOptionsForDay(currentStore, selectedDay) : [['off', TU_SHIFT_KINDS.off], ['ferie', TU_SHIFT_KINDS.ferie]];
  const blocksForCurrentStore = (emp, dayIdx) => employeeBlocksForDay(emp, dayIdx, ctx).filter(b => (b.storeId || emp.storeId) === ctx.currentStoreId);
  const blocksForOtherStores = (emp, dayIdx) => employeeBlocksForDay(emp, dayIdx, ctx).filter(b => (b.storeId || emp.storeId) !== ctx.currentStoreId);
  const blockHours = (blocks) => blocks.reduce((sum, b) => sum + hoursBetween(b.start, b.end), 0);
  const blockLabel = (blocks) => blocks.map(b => `${b.start}-${b.end}`).join(' / ');
  const dayRows = companyTeam.map(emp => {
    const cell = (ctx.schedule[emp.id] || [])[selectedDay] || 'off';
    const normalized = normalizeShiftCell(cell, homeStoreFor(emp), selectedDay, emp.storeId);
    const currentBlocks = blocksForCurrentStore(emp, selectedDay);
    const otherBlocks = blocksForOtherStores(emp, selectedDay);
    const assignedElsewhere = otherBlocks.length > 0;
    const hours = blockHours(currentBlocks);
    return {
      emp,
      cell,
      status: normalized.status === 'ferie' ? 'ferie' : (hours > 0 ? 'work' : (assignedElsewhere ? 'other' : 'off')),
      label: normalized.status === 'ferie' ? 'Ferie' : (hours > 0 ? blockLabel(currentBlocks) : (assignedElsewhere ? `Altro: ${storeName(otherBlocks[0].storeId)}` : 'Disponibile')),
      hours,
    };
  });
  const presentRows = dayRows.filter(r => r.status === 'work');
  const dayHours = dayRows.reduce((sum, r) => sum + r.hours, 0);
  const expected = expectedFor(selectedDay);

  const setShift = (emp, kind) => {
    if (readOnly) return;
    const value = (kind === 'off' || kind === 'ferie') ? kind : makeWorkShift(currentStore, selectedDay, kind, ctx.currentStoreId);
    ctx.updateShift(emp.id, selectedDay, value);
  };
  const totalHoursFor = (emp) => (ctx.schedule[emp.id] || []).reduce((s, k, i) => s + shiftCellHours(k, homeStoreFor(emp), i, emp.storeId), 0);
  const dropShift = (emp) => {
    if (!dragKind || readOnly) return;
    setShift(emp, dragKind);
    setDragKind(null);
    setHoverEmpId(null);
  };

  return (
    <>
      <DesktopTopbar
        title="Pianificazione turni"
        subtitle={`${currentStore?.name || 'Nessun negozio selezionato'} - ${currentCompany?.name || 'Societa'} - ${TU_WEEK_LABEL}`}
        actions={readOnly ? <span className="tu-chip">Sola lettura</span> : <>{confirmMsg && <span className="tu-chip" style={{ background: 'var(--ok-soft)', color: 'var(--ok)' }}>{confirmMsg}</span>}<button className="tu-btn tu-btn-primary" onClick={handleConfirmWeek}><TuIcon.check size={16}/> Conferma settimana</button></>}
      />
      <div style={{ flex: 1, display: 'flex', overflow: 'hidden', background: 'var(--bg)' }}>
        <PlannerStoresDaySidebar user={user} selectedDay={selectedDay} setSelectedDay={setSelectedDay} compact/>

        <main style={{ flex: 1, minWidth: 0, overflow: 'auto', padding: 24 }}>
          <div style={{ maxWidth: 1120, margin: '0 auto', display: 'flex', flexDirection: 'column', gap: 16 }}>
            <section style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
              <div style={{ background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 8, padding: 18 }}>
                <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16 }}>
                  <div>
                    <div className="tu-tiny">Giornata selezionata</div>
                    <div style={{ fontSize: 28, fontWeight: 850, letterSpacing: 0, marginTop: 4 }}>{TU_DAYS_LONG[selectedDay]} {TU_WEEK_DATES[selectedDay]} {TU_MONTHS[new Date(TU_WEEK_MONDAY.getTime() + selectedDay * 86400000).getMonth()]}</div>
                    <div style={{ fontSize: 13, color: 'var(--ink-3)', marginTop: 6 }}>{currentStore?.name || 'Seleziona un negozio'} - {dayOpenBlocks.length ? openingLabel(dayOpenBlocks) : 'chiuso'}</div>
                  </div>
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, minmax(74px, 1fr))', gap: 8, minWidth: 260 }}>
                    <PlannerMetric label="Presenti" value={presentRows.length}/>
                    <PlannerMetric label="Ore" value={`${dayHours}h`}/>
                    <PlannerMetric label="Copertura" value={expected ? (dayHours >= expected ? 'OK' : `-${expected - dayHours}h`) : 'Chiuso'} tone={expected && dayHours < expected ? 'warn' : 'ok'}/>
                  </div>
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 6, marginTop: 18 }}>
                  {TU_DAYS_SHORT.map((d, i) => {
                    const active = selectedDay === i;
                    return (
                      <button key={d} onClick={() => setSelectedDay(i)}
                        style={{ height: 48, borderRadius: 8, border: `1px solid ${active ? 'var(--primary)' : 'var(--line)'}`, background: active ? 'var(--primary)' : 'var(--bg)', color: active ? '#fff' : 'var(--ink-2)', fontWeight: 850, cursor: 'pointer' }}>
                        <div style={{ fontSize: 12 }}>{d}</div>
                        <div style={{ fontSize: 10, opacity: .75 }}>{TU_WEEK_DATES[i]}</div>
                      </button>
                    );
                  })}
                </div>
                {!readOnly && (
                  <div style={{ marginTop: 16, padding: 14, border: '1px solid var(--line)', borderRadius: 8, background: 'var(--bg)' }}>
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, marginBottom: 10 }}>
                      <div>
                        <div className="tu-tiny">Trascina da qui</div>
                        <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginTop: 2 }}>Prendi un turno e rilascialo sulla riga dell'addetto.</div>
                      </div>
                      {dragKind && <div style={{ fontSize: 12, color: 'var(--primary-deep)', fontWeight: 850 }}>Rilascia sulla riga desiderata</div>}
                    </div>
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                      {shiftOptions.map(([k, meta]) => (
                        <div key={k} draggable
                          onDragStart={() => setDragKind(k)}
                          onDragEnd={() => { setDragKind(null); setHoverEmpId(null); }}
                          className={`tu-shift ${TU_SHIFT_KINDS[k]?.cls || 'tu-shift-off'}`}
                          style={{ cursor: 'grab', minHeight: 48, borderRadius: 10, display: 'flex', alignItems: 'center', gap: 10, padding: '8px 12px', fontSize: 12, fontWeight: 850, boxShadow: '0 6px 14px rgba(31,27,23,.08)' }}>
                          <TuIcon.swap size={14}/>
                          <span>
                            <span style={{ display: 'block' }}>{meta.label}</span>
                            <span style={{ display: 'block', fontSize: 11, opacity: .72, marginTop: 1 }}>{meta.start ? `${meta.start}-${meta.end}` : 'trascina'}</span>
                          </span>
                        </div>
                      ))}
                    </div>
                  </div>
                )}
              </div>

              <div style={{ background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 8, overflow: 'hidden' }}>
                <div style={{ display: 'grid', gridTemplateColumns: '1.25fr .9fr 1.15fr 90px', gap: 12, padding: '11px 16px', background: 'var(--bg-2)', borderBottom: '1px solid var(--line)', color: 'var(--ink-3)', fontSize: 11, fontWeight: 900, textTransform: 'uppercase' }}>
                  <div>Staff azienda</div>
                  <div>Turno attuale</div>
                  <div>Assegna qui</div>
                  <div style={{ textAlign: 'right' }}>Totale</div>
                </div>
                {dayRows.length === 0 && <div style={{ padding: 34, textAlign: 'center', color: 'var(--ink-3)', fontWeight: 700 }}>Nessun addetto nella societa di questo negozio.</div>}
                {dayRows.map(({ emp, cell, status, label, hours }) => (
                  <div key={emp.id}
                    onDragOver={readOnly ? undefined : (e => { e.preventDefault(); setHoverEmpId(emp.id); })}
                    onDragLeave={readOnly ? undefined : (() => setHoverEmpId(null))}
                    onDrop={readOnly ? undefined : (() => dropShift(emp))}
                    style={{ display: 'grid', gridTemplateColumns: '1.25fr .9fr 1.15fr 90px', gap: 12, alignItems: 'center', padding: '14px 16px', borderBottom: '1px solid var(--line)', background: hoverEmpId === emp.id ? '#fff8d8' : (status === 'work' ? '#fff' : 'rgba(248,247,244,.54)'), outline: hoverEmpId === emp.id ? '2px solid var(--primary)' : 'none', outlineOffset: -2 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
                      <TuAvatar name={emp.name} size={34}/>
                      <div style={{ minWidth: 0 }}>
                        <div style={{ fontSize: 14, fontWeight: 850, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{emp.name}</div>
                        <div style={{ fontSize: 11.5, color: 'var(--ink-3)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                          Base: {storeName(emp.storeId)} - {emp.contract}
                        </div>
                      </div>
                    </div>
                    <div className={`tu-shift ${status === 'other' ? 'tu-shift-off' : shiftCellClass(cell, currentStore, selectedDay)}`} style={{ minHeight: 40, borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center', textAlign: 'center', fontSize: 12, fontWeight: 850, padding: '6px 8px' }}>
                      {label}
                    </div>
                    <div style={{ minHeight: 42, border: `1px dashed ${hoverEmpId === emp.id ? 'var(--primary)' : 'var(--line-2)'}`, borderRadius: 8, background: hoverEmpId === emp.id ? 'var(--primary-soft)' : 'var(--bg)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: hoverEmpId === emp.id ? 'var(--primary-deep)' : 'var(--ink-3)', fontSize: 12, fontWeight: 850 }}>
                      {readOnly ? 'Sola lettura' : (dragKind ? 'Rilascia qui' : 'Trascina qui')}
                    </div>
                    <div style={{ textAlign: 'right' }}>
                      <div style={{ fontSize: 14, fontWeight: 900 }}>{hours}h</div>
                      <div style={{ fontSize: 10.5, color: totalHoursFor(emp) > emp.hours ? 'var(--danger)' : 'var(--ink-4)', fontWeight: 800 }}>{totalHoursFor(emp)}/{emp.hours}h</div>
                    </div>
                  </div>
                ))}
              </div>
            </section>

            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10 }}>
              {[
                ['1. Scegli il giorno', 'Usa i pulsanti sopra la giornata.'],
                ['2. Prendi un turno', 'Trascinalo dalla palette in alto.'],
                ['3. Rilascialo', 'Mollalo sulla riga dell’operatore.'],
              ].map(([title, body]) => (
                <div key={title} style={{ background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 8, padding: 14 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 850 }}>{title}</div>
                  <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 4 }}>{body}</div>
                </div>
              ))}
            </div>
          </div>
        </main>
      </div>
    </>
  );
};

// Final planner override: drag people from the company pool into daily store columns.
DesktopPlanner = function DesktopPlannerPeopleToStores({ user }) {
  const ctx = useTurni();
  const currentStore = ctx.currentStore;
  const currentCompanyId = currentStore?.companyId || ctx.companies[0]?.id || '';
  const currentCompany = ctx.companies.find(c => c.id === currentCompanyId);
  const companyStores = ctx.stores.filter(s => s.companyId === currentCompanyId && ctx.visibleStoreIds(user).includes(s.id));
  const editableStoreIds = ctx.editableStoreIds(user);
  const employeeCompanyId = (emp) => emp.companyId || ctx.stores.find(s => s.id === emp.storeId)?.companyId || currentCompanyId;
  const companyTeam = ctx.team.filter(emp => employeeCompanyId(emp) === currentCompanyId);
  const storeName = (storeId) => ctx.stores.find(s => s.id === storeId)?.name || 'Negozio non indicato';
  const [selectedDay, setSelectedDay] = useState(0);
  const [dragEmpId, setDragEmpId] = useState(null);
  const [hoverStoreId, setHoverStoreId] = useState(null);
  const [assignDraft, setAssignDraft] = useState(null);
  const [copyMessage, setCopyMessage] = useState('');
  const [confirmMsg, setConfirmMsg] = useState('');
  const handleConfirmWeek = async () => {
    const r = await ctx.confirmWeek?.(ctx.currentStoreId).catch(() => null);
    const n = r?.notified ?? 0;
    setConfirmMsg(n > 0 ? `Notificati ${n} addetti` : 'Nessuna push (Web Push non attivo o nessun addetto)');
    setTimeout(() => setConfirmMsg(''), 4000);
  };

  const storeRows = (store) => employeesInStoreForDay(store.id, selectedDay, ctx);
  const blocksLabel = (blocks) => blocks.map(b => `${b.start}-${b.end}`).join(' / ');
  const blocksHours = (blocks) => blocks.reduce((sum, b) => sum + hoursBetween(b.start, b.end), 0);
  const employeeDayBlocks = (emp) => employeeBlocksForDay(emp, selectedDay, ctx);
  const assignedStoresFor = (emp) => {
    const ids = [...new Set(employeeDayBlocks(emp).map(b => b.storeId || emp.storeId))];
    return ids.map(storeName).join(', ');
  };
  const employeeWeekHours = (emp) => (ctx.schedule[emp.id] || []).reduce((sum, cell, dayIdx) => {
    const home = ctx.stores.find(s => s.id === emp.storeId) || currentStore;
    return sum + shiftCellHours(cell, home, dayIdx, emp.storeId);
  }, 0);
  const companyDayHours = companyStores.reduce((sum, store) => {
    return sum + storeRows(store).reduce((s, row) => s + blocksHours(row.blocks), 0);
  }, 0);
  const companyExpectedHours = companyStores.reduce((sum, store) => sum + expectedHoursForDay(store, selectedDay), 0);

  const startAssignment = (emp, store) => {
    if (!emp || !store || !editableStoreIds.includes(store.id)) return;
    const firstBlock = openingBlocksFor(store, selectedDay)[0] || { start: '09:00', end: '13:00' };
    setAssignDraft({
      emp,
      store,
      dayIdx: selectedDay,
      kind: 'morning',
      start: firstBlock.start,
      end: firstBlock.end,
    });
  };
  const dropOnStore = (store) => {
    const emp = companyTeam.find(e => e.id === dragEmpId);
    startAssignment(emp, store);
    setDragEmpId(null);
    setHoverStoreId(null);
  };
  const saveAssignment = () => {
    if (!assignDraft) return;
    const { emp, store, dayIdx, kind, start, end } = assignDraft;
    const value = kind === 'manual'
      ? { status: 'work', preset: 'manual', blocks: [{ start, end, storeId: store.id }] }
      : makeWorkShift(store, dayIdx, kind, store.id);
    ctx.updateShift(emp.id, dayIdx, value);
    setAssignDraft(null);
  };
  const removeAssignment = (emp) => ctx.updateShift(emp.id, selectedDay, 'off');
  const copyWeekForward = () => {
    setCopyMessage('Copia settimana pronta come flusso: manca solo la gestione archivio settimane nel database.');
    window.setTimeout(() => setCopyMessage(''), 4200);
  };

  return (
    <>
      {assignDraft && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 100, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(31,27,23,.45)', backdropFilter: 'blur(6px)' }}
          onClick={() => setAssignDraft(null)}>
          <div style={{ width: 500, background: 'var(--surface)', borderRadius: 22, padding: 28, boxShadow: '0 40px 80px rgba(0,0,0,.25)' }}
            onClick={e => e.stopPropagation()}>
            <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16, marginBottom: 20 }}>
              <div>
                <div className="tu-h2">Imposta orario</div>
                <div style={{ fontSize: 13, color: 'var(--ink-3)', marginTop: 4 }}>
                  {assignDraft.emp.name} - {assignDraft.store.name} - {TU_DAYS_LONG[assignDraft.dayIdx]}
                </div>
              </div>
              <button onClick={() => setAssignDraft(null)} title="Chiudi"
                style={{ width: 32, height: 32, border: '1px solid var(--line)', background: 'var(--surface)', borderRadius: 8, color: 'var(--ink-2)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}>
                <TuIcon.x size={14}/>
              </button>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 8, marginBottom: 16 }}>
              {shiftOptionsForDay(assignDraft.store, assignDraft.dayIdx)
                .filter(([k]) => k !== 'off' && k !== 'ferie')
                .map(([k, meta]) => (
                  <button key={k} onClick={() => setAssignDraft(d => ({ ...d, kind: k, start: meta.start || d.start, end: meta.end || d.end }))}
                    style={{ minHeight: 54, borderRadius: 10, border: `1px solid ${assignDraft.kind === k ? 'var(--primary)' : 'var(--line)'}`, background: assignDraft.kind === k ? 'var(--primary-soft)' : 'var(--bg)', color: assignDraft.kind === k ? 'var(--primary-deep)' : 'var(--ink)', cursor: 'pointer', textAlign: 'left', padding: '8px 10px' }}>
                    <div style={{ fontSize: 13, fontWeight: 850 }}>{meta.label}</div>
                    <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 2 }}>{meta.start ? `${meta.start}-${meta.end}` : 'orario'}</div>
                  </button>
                ))}
              <button onClick={() => setAssignDraft(d => ({ ...d, kind: 'manual' }))}
                style={{ minHeight: 54, borderRadius: 10, border: `1px solid ${assignDraft.kind === 'manual' ? 'var(--primary)' : 'var(--line)'}`, background: assignDraft.kind === 'manual' ? 'var(--primary-soft)' : 'var(--bg)', color: assignDraft.kind === 'manual' ? 'var(--primary-deep)' : 'var(--ink)', cursor: 'pointer', textAlign: 'left', padding: '8px 10px' }}>
                <div style={{ fontSize: 13, fontWeight: 850 }}>Manuale</div>
                <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 2 }}>scegli inizio/fine</div>
              </button>
            </div>
            {assignDraft.kind === 'manual' && (
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 16 }}>
                <div>
                  <label className="tu-label">Inizio</label>
                  <input className="tu-input" type="time" value={assignDraft.start} onChange={e => setAssignDraft(d => ({ ...d, start: e.target.value }))}/>
                </div>
                <div>
                  <label className="tu-label">Fine</label>
                  <input className="tu-input" type="time" value={assignDraft.end} onChange={e => setAssignDraft(d => ({ ...d, end: e.target.value }))}/>
                </div>
              </div>
            )}
            <div style={{ display: 'flex', gap: 10 }}>
              <button className="tu-btn tu-btn-ghost" style={{ flex: 1 }} onClick={() => setAssignDraft(null)}>Annulla</button>
              <button className="tu-btn tu-btn-primary" style={{ flex: 1.6 }} onClick={saveAssignment}
                disabled={assignDraft.kind === 'manual' && timeToMinutes(assignDraft.end) <= timeToMinutes(assignDraft.start)}>
                <TuIcon.check size={16}/> Assegna
              </button>
            </div>
          </div>
        </div>
      )}

      <DesktopTopbar
        title="Pianificazione turni"
        subtitle={`${currentCompany?.name || 'Societa'} - ${TU_WEEK_LABEL}`}
        actions={
          <>
            {confirmMsg && <span className="tu-chip" style={{ background: 'var(--ok-soft)', color: 'var(--ok)' }}>{confirmMsg}</span>}
            <button className="tu-btn tu-btn-ghost" onClick={copyWeekForward}><TuIcon.swap size={16}/> Copia settimana dopo</button>
            <button className="tu-btn tu-btn-primary" onClick={handleConfirmWeek}><TuIcon.check size={16}/> Conferma settimana</button>
          </>
        }
      />
      <div style={{ flex: 1, display: 'flex', overflow: 'hidden', background: 'var(--bg)' }}>
        <aside style={{ width: 300, flexShrink: 0, borderRight: '1px solid var(--line)', background: 'var(--surface)', display: 'flex', flexDirection: 'column', minHeight: 0 }}>
          <div style={{ padding: 16, borderBottom: '1px solid var(--line)' }}>
            <div style={{ fontSize: 13, fontWeight: 900 }}>Staff azienda</div>
            <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 3 }}>Prendi una persona e trascinala in un negozio.</div>
          </div>
          <div style={{ padding: 12, display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 5, borderBottom: '1px solid var(--line)' }}>
            {TU_DAYS_SHORT.map((d, i) => {
              const active = selectedDay === i;
              return (
                <button key={d} onClick={() => setSelectedDay(i)}
                  style={{ height: 38, borderRadius: 8, border: `1px solid ${active ? 'var(--primary)' : 'var(--line)'}`, background: active ? 'var(--primary)' : 'var(--bg)', color: active ? '#fff' : 'var(--ink-3)', fontSize: 10.5, fontWeight: 850, cursor: 'pointer' }}>
                  {d}
                </button>
              );
            })}
          </div>
          <div style={{ flex: 1, overflow: 'auto', padding: 12, display: 'flex', flexDirection: 'column', gap: 8 }}>
            {companyTeam.length === 0 && <div style={{ padding: 18, color: 'var(--ink-3)', fontSize: 13 }}>Nessun addetto nella societa.</div>}
            {companyTeam.map(emp => {
              const assigned = assignedStoresFor(emp);
              return (
                <div key={emp.id} draggable
                  onDragStart={() => setDragEmpId(emp.id)}
                  onDragEnd={() => { setDragEmpId(null); setHoverStoreId(null); }}
                  style={{ border: '1px solid var(--line)', borderRadius: 8, background: dragEmpId === emp.id ? 'var(--primary-soft)' : 'var(--bg)', padding: 10, cursor: 'grab', display: 'flex', alignItems: 'center', gap: 10 }}>
                  <TuAvatar name={emp.name} size={34}/>
                  <div style={{ minWidth: 0, flex: 1 }}>
                    <div style={{ fontSize: 13.5, fontWeight: 850, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{emp.name}</div>
                    <div style={{ fontSize: 11, color: 'var(--ink-3)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>Base: {storeName(emp.storeId)}</div>
                    <div style={{ fontSize: 10.5, color: assigned ? 'var(--primary-deep)' : 'var(--ink-4)', marginTop: 3 }}>{assigned || 'Disponibile oggi'} - {employeeWeekHours(emp)}/{emp.hours}h</div>
                  </div>
                </div>
              );
            })}
          </div>
        </aside>

        <main style={{ flex: 1, minWidth: 0, overflow: 'auto', padding: 22 }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16, marginBottom: 16 }}>
            <div>
              <div className="tu-tiny">Giornata selezionata</div>
              <div style={{ fontSize: 28, fontWeight: 850, letterSpacing: 0, marginTop: 4 }}>{TU_DAYS_LONG[selectedDay]} {TU_WEEK_DATES[selectedDay]} {TU_MONTHS[new Date(TU_WEEK_MONDAY.getTime() + selectedDay * 86400000).getMonth()]}</div>
              <div style={{ fontSize: 13, color: 'var(--ink-3)', marginTop: 5 }}>Trascina le persone nei negozi della societa.</div>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, minmax(90px, 1fr))', gap: 8, minWidth: 300 }}>
              <PlannerMetric label="Negozi" value={companyStores.length}/>
              <PlannerMetric label="Ore pianif." value={`${companyDayHours}h`}/>
              <PlannerMetric label="Copertura" value={companyExpectedHours ? (companyDayHours >= companyExpectedHours ? 'OK' : `-${companyExpectedHours - companyDayHours}h`) : 'Chiuso'} tone={companyExpectedHours && companyDayHours < companyExpectedHours ? 'warn' : 'ok'}/>
            </div>
          </div>
          {copyMessage && (
            <div style={{ marginBottom: 14, border: '1px solid var(--line)', background: 'var(--primary-soft)', color: 'var(--primary-deep)', borderRadius: 8, padding: '10px 12px', fontSize: 12.5, fontWeight: 750 }}>
              {copyMessage}
            </div>
          )}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))', gap: 12, alignItems: 'start' }}>
            {companyStores.map(store => {
              const rows = storeRows(store);
              const open = openingBlocksFor(store, selectedDay);
              const canDrop = editableStoreIds.includes(store.id);
              const hover = hoverStoreId === store.id && dragEmpId;
              return (
                <section key={store.id}
                  onDragOver={canDrop ? (e => { e.preventDefault(); setHoverStoreId(store.id); }) : undefined}
                  onDragLeave={canDrop ? (() => setHoverStoreId(null)) : undefined}
                  onDrop={canDrop ? (() => dropOnStore(store)) : undefined}
                  style={{ minHeight: 260, border: `1px solid ${hover ? 'var(--primary)' : 'var(--line)'}`, borderRadius: 8, background: hover ? 'var(--primary-soft)' : 'var(--surface)', overflow: 'hidden', boxShadow: hover ? '0 14px 28px rgba(26,95,183,.16)' : 'none' }}>
                  <div style={{ padding: 14, borderBottom: '1px solid var(--line)', background: '#fff' }}>
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10 }}>
                      <div style={{ minWidth: 0 }}>
                        <div style={{ fontSize: 16, fontWeight: 900, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{store.name}</div>
                        <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 3 }}>{open.length ? openingLabel(open) : 'Chiuso'}</div>
                      </div>
                      <span className={`tu-chip ${rows.length ? 'tu-chip-ok' : ''}`}>{rows.length}</span>
                    </div>
                  </div>
                  <div style={{ padding: 12, display: 'flex', flexDirection: 'column', gap: 8 }}>
                    {rows.length === 0 && (
                      <div style={{ border: '1px dashed var(--line-2)', borderRadius: 8, minHeight: 90, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--ink-3)', fontSize: 12.5, fontWeight: 800 }}>
                        {dragEmpId ? 'Rilascia qui' : 'Trascina una persona qui'}
                      </div>
                    )}
                    {rows.map(({ emp, blocks }) => (
                      <div key={`${store.id}-${emp.id}`} style={{ border: '1px solid var(--line)', borderRadius: 8, background: '#fff', padding: 10, display: 'flex', alignItems: 'center', gap: 10 }}>
                        <TuAvatar name={emp.name} size={30}/>
                        <div style={{ minWidth: 0, flex: 1 }}>
                          <div style={{ fontSize: 13, fontWeight: 850, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{emp.name}</div>
                          <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{blocksLabel(blocks)} - {blocksHours(blocks)}h</div>
                        </div>
                        <div style={{ display: 'flex', gap: 6 }}>
                          <button onClick={() => startAssignment(emp, store)} title="Modifica orario"
                            style={{ width: 30, height: 30, border: '1px solid var(--line)', background: 'var(--surface)', borderRadius: 8, color: 'var(--ink-2)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}>
                            <TuIcon.edit size={13}/>
                          </button>
                          <button onClick={() => removeAssignment(emp)} title="Rimuovi dal giorno"
                            style={{ width: 30, height: 30, border: '1px solid var(--line)', background: 'var(--surface)', borderRadius: 8, color: 'var(--danger)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}>
                            <TuIcon.x size={13}/>
                          </button>
                        </div>
                      </div>
                    ))}
                  </div>
                </section>
              );
            })}
          </div>
        </main>
      </div>
    </>
  );
};

Object.assign(window, { DesktopDashboard, DesktopPlanner, DesktopTeam, DesktopStructure });
