// ClosingScreen.jsx — Daily Closing checklist
// Minimal Apple-inspired design. All-neutral, no gradients.
// Two layout variants (Tweaks):
//   A) Table view: paper-faithful table with step chips
//   B) Zone-guided: pick a zone → step-by-step cards

const { useState: useClose, useMemo: useMemoClose } = React;

const STEP_META = {
  preclose:  { label: 'Pre-Close',         short: 'P' },
  preclose2: { label: 'Partial Pre-Close', short: 'p' },
  restock:   { label: 'Restock',           short: 'R' },
  clean:     { label: 'Clean',             short: 'C' },
  closeoff:  { label: 'Close / Off',       short: '×' },
};

const StepIconBadge = ({ step, size = 24, done = false }) => {
  const m = STEP_META[step];
  return (
    <div style={{
      width: size, height: size, borderRadius: 6,
      background: done ? 'var(--fg-1)' : 'transparent',
      color: done ? '#FFFFFF' : 'var(--fg-1)',
      border: done ? '1px solid var(--fg-1)' : '1px solid var(--border-1)',
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      fontSize: size * 0.55,
      fontWeight: 500,
      letterSpacing: '-0.01em',
      flexShrink: 0,
      fontFamily: 'var(--font-ui)',
    }}>
      {m.short}
    </div>
  );
};

const Legend = () => (
  <div style={{
    display: 'flex', gap: 18, flexWrap: 'wrap',
    padding: '12px 16px',
    background: 'var(--bg-surface)',
    border: '1px solid var(--border-1)',
    borderRadius: 12,
  }}>
    {Object.keys(STEP_META).map(k => (
      <div key={k} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <StepIconBadge step={k} size={22} />
        <span style={{ fontSize: 12, fontWeight: 500, color: 'var(--fg-2)' }}>{STEP_META[k].label}</span>
      </div>
    ))}
  </div>
);

// ------------------------------------------------------------------
// Step chip — minimal toggle
// ------------------------------------------------------------------
const StepChip = ({ step, state, onToggle, compact }) => {
  const m = STEP_META[step];
  const done = state?.done;
  const staff = done ? window.SAMPLE_STAFF.find(s => s.id === state.staffId) : null;
  return (
    <button onClick={onToggle} style={{
      display: 'inline-flex', alignItems: 'center', gap: 8,
      padding: compact ? '4px 8px' : '5px 10px 5px 6px',
      borderRadius: 8,
      background: done ? 'var(--bg-sunken)' : 'transparent',
      border: `1px solid ${done ? 'var(--border-1)' : 'var(--border-1)'}`,
      transition: 'all 140ms',
    }}>
      <StepIconBadge step={step} size={compact ? 20 : 22} done={done} />
      {!compact && (
        <span style={{ fontSize: 12, fontWeight: 500, color: done ? 'var(--fg-1)' : 'var(--fg-2)' }}>
          {m.label}
        </span>
      )}
      {staff && <Avatar staff={staff} size={18} style={{ marginLeft: 2 }} />}
    </button>
  );
};

// ------------------------------------------------------------------
// Layout A — table
// ------------------------------------------------------------------
const PaperLayout = ({ onBack, closingState, toggle }) => {
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      <ClosingHeader onBack={onBack} closingState={closingState} />
      <div className="scroll-soft" style={{ flex: 1, overflowY: 'auto', padding: '16px 24px 32px' }}>
        <div style={{ marginBottom: 14 }}>
          <Legend />
        </div>
        {window.SAMPLE_CLOSING.map(zone => {
          const total = zone.tasks.reduce((a, t) => a + t.steps.length, 0);
          const done = zone.tasks.reduce((a, t) => {
            const state = closingState[t.id] || {};
            return a + t.steps.filter(s => state[s]?.done).length;
          }, 0);
          const pct = Math.round((done / total) * 100);
          return (
            <div key={zone.zone} style={{ marginBottom: 16 }}>
              <div style={{
                display: 'flex', alignItems: 'center', gap: 12,
                padding: '0 4px 8px',
              }}>
                <div style={{ fontSize: 14, fontWeight: 600, letterSpacing: '-0.01em', color: 'var(--fg-1)' }}>{zone.zone}</div>
                <div style={{ flex: 1 }} />
                <div style={{ fontSize: 11, fontWeight: 500, color: 'var(--fg-2)', fontFamily: 'var(--font-num)' }}>{done}/{total}</div>
                <div style={{ width: 64 }}>
                  <ProgressBar pct={pct} height={2} color="var(--fg-1)" bg="var(--border-1)" />
                </div>
              </div>
              <div style={{
                background: 'var(--bg-surface)',
                borderRadius: 10,
                border: '1px solid var(--border-1)',
                overflow: 'hidden',
              }}>
                {zone.tasks.map((task, idx) => {
                  const state = closingState[task.id] || {};
                  const allDone = task.steps.every(s => state[s]?.done);
                  return (
                    <div key={task.id} style={{
                      display: 'flex', alignItems: 'center', gap: 12,
                      padding: '8px 14px',
                      borderBottom: idx < zone.tasks.length - 1 ? '1px solid var(--border-2)' : 'none',
                    }}>
                      <div style={{
                        flex: 1, fontSize: 13, fontWeight: 500,
                        color: allDone ? 'var(--fg-3)' : 'var(--fg-1)',
                        textDecoration: allDone ? 'line-through' : 'none',
                      }}>
                        {task.name}
                      </div>
                      <div style={{ display: 'flex', gap: 4 }}>
                        {task.steps.map(step => (
                          <StepChip
                            key={step} step={step}
                            state={state[step]}
                            onToggle={() => toggle(task.id, step)}
                            compact
                          />
                        ))}
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

// ------------------------------------------------------------------
// Layout B — zone-guided
// ------------------------------------------------------------------
const GuidedLayout = ({ onBack, closingState, toggle }) => {
  const [activeZone, setActiveZone] = React.useState(null);

  if (!activeZone) {
    return (
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
        <ClosingHeader onBack={onBack} closingState={closingState} />
        <div className="scroll-soft" style={{ flex: 1, overflowY: 'auto', padding: '20px 24px 40px' }}>
          <Legend />
          <div style={{ marginTop: 20, display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 12 }}>
            {window.SAMPLE_CLOSING.map(zone => {
              const total = zone.tasks.reduce((a, t) => a + t.steps.length, 0);
              const done = zone.tasks.reduce((a, t) => {
                const state = closingState[t.id] || {};
                return a + t.steps.filter(s => state[s]?.done).length;
              }, 0);
              const pct = Math.round((done / total) * 100);
              const allDone = done === total;
              return (
                <button key={zone.zone} onClick={() => setActiveZone(zone)} style={{
                  textAlign: 'left', padding: 20,
                  background: 'var(--bg-surface)',
                  borderRadius: 14,
                  border: '1px solid var(--border-1)',
                }}>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
                    <div style={{ fontSize: 18, fontWeight: 600, letterSpacing: '-0.015em', color: 'var(--fg-1)' }}>{zone.zone}</div>
                    {allDone && <Icon name="check" size={18} color="var(--fg-1)" strokeWidth={1.8} />}
                  </div>
                  <div style={{ fontSize: 13, color: 'var(--fg-2)', marginBottom: 12, fontWeight: 400 }}>
                    {zone.tasks.length} tasks · {total} steps
                  </div>
                  <ProgressBar pct={pct} height={3} color="var(--fg-1)" bg="var(--border-1)" />
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 12 }}>
                    <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--fg-2)', fontFamily: 'var(--font-num)' }}>
                      {done}/{total}
                    </div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 13, fontWeight: 500, color: 'var(--fg-1)' }}>
                      {allDone ? 'Review' : 'Open'} <Icon name="chevron" size={14} strokeWidth={1.8} />
                    </div>
                  </div>
                </button>
              );
            })}
          </div>
        </div>
      </div>
    );
  }

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      <div style={{
        padding: '20px 24px 18px',
        background: 'var(--bg-surface)',
        borderBottom: '1px solid var(--border-1)',
        display: 'flex', alignItems: 'center', gap: 16,
      }}>
        <button onClick={() => setActiveZone(null)} className="tap" style={{
          width: 36, height: 36, borderRadius: 10,
          background: 'var(--bg-sunken)',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <Icon name="chevronL" size={18} color="var(--fg-1)" strokeWidth={1.8} />
        </button>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 11, color: 'var(--fg-3)', fontWeight: 500, letterSpacing: '0.06em', textTransform: 'uppercase' }}>Closing zone</div>
          <div style={{ fontSize: 22, fontWeight: 600, letterSpacing: '-0.02em', color: 'var(--fg-1)' }}>{activeZone.zone}</div>
        </div>
      </div>
      <div className="scroll-soft" style={{ flex: 1, overflowY: 'auto', padding: '20px 24px 40px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(360px, 1fr))', gap: 12 }}>
          {activeZone.tasks.map(task => {
            const state = closingState[task.id] || {};
            const allDone = task.steps.every(s => state[s]?.done);
            const doneCount = task.steps.filter(s => state[s]?.done).length;
            return (
              <div key={task.id} style={{
                background: 'var(--bg-surface)',
                borderRadius: 14, padding: 16,
                border: '1px solid var(--border-1)',
              }}>
                <div style={{ display: 'flex', alignItems: 'start', justifyContent: 'space-between', gap: 12 }}>
                  <div style={{ fontSize: 15, fontWeight: 500, letterSpacing: '-0.005em', color: allDone ? 'var(--fg-3)' : 'var(--fg-1)', flex: 1, textDecoration: allDone ? 'line-through' : 'none' }}>
                    {task.name}
                  </div>
                  <div style={{ fontSize: 12, color: 'var(--fg-3)', fontWeight: 500, whiteSpace: 'nowrap', fontFamily: 'var(--font-num)' }}>
                    {doneCount}/{task.steps.length}
                  </div>
                </div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 14 }}>
                  {task.steps.map(step => (
                    <StepChip
                      key={step} step={step}
                      state={state[step]}
                      onToggle={() => toggle(task.id, step)}
                    />
                  ))}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
};

// ------------------------------------------------------------------
// Shared header
// ------------------------------------------------------------------
const ClosingHeader = ({ onBack, closingState }) => {
  const total = window.SAMPLE_CLOSING.reduce((a, z) => a + z.tasks.reduce((b, t) => b + t.steps.length, 0), 0);
  const done = Object.values(closingState).reduce((a, t) => a + Object.values(t).filter(s => s.done).length, 0);
  const pct = Math.round((done / total) * 100);
  const contributors = Array.from(new Set(
    Object.values(closingState).flatMap(t => Object.values(t).filter(s => s.done).map(s => s.staffId))
  ));
  return (
    <div style={{
      padding: '20px 24px 20px',
      background: 'var(--bg-surface)',
      borderBottom: '1px solid var(--border-1)',
      display: 'flex', alignItems: 'center', gap: 16,
    }}>
      
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 11, color: 'var(--fg-3)', fontWeight: 500, letterSpacing: '0.06em', textTransform: 'uppercase' }}>
          Tonight · {new Date().toLocaleDateString('en-US', { weekday: 'long' })}
        </div>
        <div style={{ fontSize: 22, fontWeight: 600, letterSpacing: '-0.02em', color: 'var(--fg-1)', marginTop: 2 }}>Daily Closing</div>
      </div>
      <div style={{ textAlign: 'right' }}>
        <div style={{ fontSize: 10, fontWeight: 500, letterSpacing: '0.06em', color: 'var(--fg-3)', textTransform: 'uppercase' }}>
          Crew
        </div>
        <div style={{ marginTop: 4 }}>
          {contributors.length > 0 ? <AvatarStack ids={contributors} size={22} max={5} /> : <span style={{ fontSize: 12, color: 'var(--fg-3)' }}>—</span>}
        </div>
      </div>
      <div style={{ width: 140, padding: '6px 12px', background: 'var(--bg-sunken)', borderRadius: 10 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
          <div style={{ fontSize: 16, fontWeight: 600, fontFamily: 'var(--font-num)', letterSpacing: '-0.02em', color: 'var(--fg-1)' }}>{pct}%</div>
          <div style={{ fontSize: 11, color: 'var(--fg-2)', fontWeight: 500, fontFamily: 'var(--font-num)' }}>{done}/{total}</div>
        </div>
        <div style={{ marginTop: 5 }}>
          <ProgressBar pct={pct} height={3} color="var(--fg-1)" bg="var(--border-1)" />
        </div>
      </div>
    </div>
  );
};

// ------------------------------------------------------------------
// Main
// ------------------------------------------------------------------
const ClosingScreen = ({ onBack, closingState, setClosingState, layoutMode, setLayoutMode, currentStaff, showToast }) => {
  const toggle = (taskId, step) => {
    const state = closingState[taskId]?.[step];
    if (state?.done) {
      setClosingState(prev => {
        const next = { ...prev };
        const task = { ...(next[taskId] || {}) };
        delete task[step];
        if (Object.keys(task).length === 0) delete next[taskId];
        else next[taskId] = task;
        return next;
      });
      return;
    }
    const ts = new Date().toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: false });
    setClosingState(prev => ({
      ...prev,
      [taskId]: {
        ...(prev[taskId] || {}),
        [step]: { done: true, staffId: currentStaff.id, ts },
      },
    }));
    const taskName = (() => {
      for (const z of window.SAMPLE_CLOSING)
        for (const t of z.tasks) if (t.id === taskId) return t.name;
      return '';
    })();
    showToast({ message: `${STEP_META[step].label}: ${taskName}`, staff: currentStaff });
  };

  return (
    <div style={{ height: '100%', position: 'relative', display: 'flex', flexDirection: 'column' }}>
      <div style={{ position: 'relative' }}>
        <div style={{
          position: 'absolute', top: 16, right: 24, zIndex: 10,
          display: 'flex', gap: 2, padding: 3,
          background: 'var(--bg-sunken)', borderRadius: 9,
        }}>
          {[{k:'paper',label:'Table'},{k:'guided',label:'Zones'}].map(m => (
            <button key={m.k} onClick={() => setLayoutMode(m.k)} style={{
              height: 26, padding: '0 12px',
              borderRadius: 7,
              background: layoutMode === m.k ? '#FFFFFF' : 'transparent',
              color: layoutMode === m.k ? 'var(--fg-1)' : 'var(--fg-2)',
              fontSize: 12, fontWeight: 500,
              boxShadow: layoutMode === m.k ? '0 1px 2px rgba(0,0,0,0.06)' : 'none',
            }}>{m.label}</button>
          ))}
        </div>
      </div>
      <div style={{ flex: 1, minHeight: 0 }}>
      {layoutMode === 'paper'
        ? <PaperLayout onBack={onBack} closingState={closingState} toggle={toggle} />
        : <GuidedLayout onBack={onBack} closingState={closingState} toggle={toggle} />}
      </div>
    </div>
  );
};

Object.assign(window, { ClosingScreen });
