// app.jsx — Top-level shell. Tablet frame > sidebar nav > screen.

const PALETTE_OPTIONS = [
  '#E55B13', // safety orange (default)
  '#1D6FB8', // rail blue
  '#137C50', // signal green
  '#7C2D12', // boxcar / brick
  '#0E1418', // pure black
];

function deepenHex(hex) {
  const h = hex.replace('#', '');
  const r = parseInt(h.slice(0, 2), 16), g = parseInt(h.slice(2, 4), 16), b = parseInt(h.slice(4, 6), 16);
  return `#${Math.round(r * 0.78).toString(16).padStart(2, '0')}${Math.round(g * 0.78).toString(16).padStart(2, '0')}${Math.round(b * 0.78).toString(16).padStart(2, '0')}`;
}
function softenHex(hex, amt = 0.86) {
  const h = hex.replace('#', '');
  const r = parseInt(h.slice(0, 2), 16), g = parseInt(h.slice(2, 4), 16), b = parseInt(h.slice(4, 6), 16);
  const sr = Math.round(r + (255 - r) * amt), sg = Math.round(g + (255 - g) * amt), sb = Math.round(b + (255 - b) * amt);
  return `#${sr.toString(16).padStart(2, '0')}${sg.toString(16).padStart(2, '0')}${sb.toString(16).padStart(2, '0')}`;
}
function applyTheme(accent) {
  const root = document.documentElement;
  root.style.setProperty('--accent', accent);
  root.style.setProperty('--accent-deep', deepenHex(accent));
  root.style.setProperty('--accent-soft', softenHex(accent));
}

// ─── App root ────────────────────────────────────────────────
function App() {
  const [tweaks, setTweak] = useTweaks(window.__TWEAK_DEFAULTS);

  useEffect(() => {
    window.__currentTweaks = tweaks;
    window.dispatchEvent(new Event('tweaks-changed'));
    applyTheme(tweaks.accent);
    document.title = `${tweaks.companyName} — RWIC Tablet`;
  }, [tweaks]);

  useEffect(() => { applyTheme(tweaks.accent); }, []);

  return (
    <AppProvider>
      <Stage>
        <TabletFrame>
          <AuthGate />
        </TabletFrame>
        <Toaster />
      </Stage>

      <TweaksPanel title="Tweaks">
        <TweakSection label="White-label">
          <TweakText label="Company name" value={tweaks.companyName} onChange={v => setTweak('companyName', v)} placeholder="RailFlagsPro" />
          <TweakText label="Logo mark" value={tweaks.logoMark} onChange={v => setTweak('logoMark', (v || '').slice(0, 3).toUpperCase())} placeholder="RF" />
          <TweakText label="Tagline" value={tweaks.tagline} onChange={v => setTweak('tagline', v)} placeholder="RWIC Field Operations" />
        </TweakSection>

        <TweakSection label="Theme">
          <TweakColor label="Accent" value={tweaks.accent} options={PALETTE_OPTIONS} onChange={v => setTweak('accent', v)} />
        </TweakSection>

        <DemoPresetSection setTweak={setTweak} />

        <AuthSection />
      </TweaksPanel>
    </AppProvider>
  );
}

// Tweaks-panel section to flip between Setup / Login / App for the demo
function AuthSection() {
  return (
    <AppCtx.Consumer>
      {(ctx) => ctx ? (
        <TweakSection label="Demo state">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {[
              { v: 'setup',  label: 'Setup wizard' },
              { v: 'login',  label: 'PIN login' },
              { v: 'ready',  label: 'In app (auto-login)' },
            ].map(o => {
              const on = ctx.authStage === o.v;
              return (
                <button key={o.v} onClick={() => {
                  if (o.v === 'ready' && !ctx.user) ctx.login('4827');
                  else if (o.v !== 'ready' && ctx.user) ctx.logout();
                  ctx.setAuthStage(o.v);
                }} style={{
                  padding: '8px 12px', borderRadius: 8,
                  background: on ? 'rgba(255,255,255,0.14)' : 'transparent',
                  border: `1px solid ${on ? 'rgba(255,255,255,0.25)' : 'rgba(255,255,255,0.10)'}`,
                  color: '#fff', textAlign: 'left',
                  fontSize: 13, fontWeight: on ? 600 : 500,
                  cursor: 'pointer',
                }}>{o.label}</button>
              );
            })}
          </div>
        </TweakSection>
      ) : null}
    </AppCtx.Consumer>
  );
}

// Tweaks-panel preset list
function DemoPresetSection({ setTweak }) {
  return (
    <TweakSection label="Demo presets">
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8, padding: '4px 0' }}>
        {[
          { name: 'RailFlagsPro',   mark: 'RF', tag: 'RWIC Field Operations',  accent: '#E55B13' },
          { name: 'Granite Pacific',mark: 'GP', tag: 'Roadway Worker Suite',   accent: '#1D6FB8' },
          { name: 'SafeTrack Co',   mark: 'ST', tag: 'Field Operations',       accent: '#137C50' },
          { name: 'Boxcar Ops',     mark: 'BC', tag: 'Crew Management',        accent: '#7C2D12' },
        ].map(p => (
          <button key={p.name} onClick={() => setTweak({ companyName: p.name, logoMark: p.mark, tagline: p.tag, accent: p.accent })}
            style={{
              display: 'flex', alignItems: 'center', gap: 10,
              padding: 10, borderRadius: 10,
              background: 'transparent',
              border: '1px solid rgba(255,255,255,0.12)',
              cursor: 'pointer', width: '100%', textAlign: 'left',
              color: '#fff',
            }}>
            <div style={{
              width: 32, height: 32, borderRadius: 8, background: '#0E1418', color: '#fff',
              display: 'grid', placeItems: 'center', fontWeight: 700, fontSize: 12,
              position: 'relative', overflow: 'hidden', flexShrink: 0,
            }}>
              <div style={{ position: 'absolute', inset: 0, background: p.accent, clipPath: 'polygon(0 100%, 100% 100%, 100% 60%, 0 92%)' }} />
              <span style={{ position: 'relative', zIndex: 1 }}>{p.mark}</span>
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontWeight: 600, fontSize: 13 }}>{p.name}</div>
              <div style={{ fontSize: 11.5, opacity: 0.65 }}>{p.tag}</div>
            </div>
          </button>
        ))}
      </div>
    </TweakSection>
  );
}

// ─── Stage — centers the tablet on a dark backdrop ─────────────
function Stage({ children }) {
  return (
    <div style={{
      minHeight: '100vh', width: '100%',
      background:
        'radial-gradient(circle at 30% 20%, #1f2630 0%, #0a0d11 60%, #06080b 100%)',
      display: 'grid', placeItems: 'center',
      padding: '20px',
    }}>
      {children}
    </div>
  );
}

// ─── AuthGate — chooses between setup/login/main app ───────────
function AuthGate() {
  const { authStage, user } = useApp();
  if (authStage === 'setup') return <SetupWizard />;
  if (authStage === 'login' || !user) return <PinLogin />;
  return <AppShell />;
}

// ─── Main app shell — sidebar nav + active screen ──────────────
function AppShell() {
  const [tab, setTab] = useState('today');
  const [auditOpen, setAuditOpen] = useState(false);
  const { user, logout, briefingSubmitted, reportSubmitted, timecardSubmitted, clockState, isMaster, auditTrail } = useApp();
  const isOn = clockState.status !== 'off';

  const tabs = [
    { id: 'today',    label: 'Today',     icon: <IconHome size={18} /> },
    { id: 'briefing', label: 'Briefing',  icon: <IconShield size={18} />,  done: briefingSubmitted },
    { id: 'report',   label: 'Field Report', icon: <IconClipboard size={18} />, done: reportSubmitted },
    { id: 'timecard', label: 'Timecard',  icon: <IconClock size={18} />, done: timecardSubmitted },
  ];

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      {/* Master-mode banner — pinned to top when active */}
      {isMaster && <MasterBanner onOpen={() => setAuditOpen(true)} count={auditTrail.length} />}

      <div style={{ flex: 1, display: 'grid', gridTemplateColumns: '232px 1fr', overflow: 'hidden' }}>
      {/* SIDEBAR */}
      <aside style={{
        background: '#0E1418',
        color: 'rgba(255,255,255,0.85)',
        display: 'flex', flexDirection: 'column',
        padding: 14,
        borderRight: '1px solid #1a212a',
      }}>
        {/* Brand */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 6px 18px' }}>
          <Mark size={32} hideText />
          <BrandLockup />
        </div>

        {/* User chip */}
        <div style={{
          background: user.isMaster ? 'rgba(180,35,24,0.18)' : 'rgba(255,255,255,0.04)',
          border: `1px solid ${user.isMaster ? 'rgba(180,35,24,0.45)' : 'rgba(255,255,255,0.08)'}`,
          borderRadius: 12, padding: '10px 12px',
          marginBottom: 18,
          display: 'flex', alignItems: 'center', gap: 10,
        }}>
          {user.isMaster ? (
            <div style={{
              width: 36, height: 36, borderRadius: '50%',
              background: 'var(--bad)', color: '#fff',
              display: 'grid', placeItems: 'center', flexShrink: 0,
            }}>
              <IconShield size={18} />
            </div>
          ) : (
            <Avatar name={user.name} size={36} />
          )}
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontWeight: 600, fontSize: 13, color: '#fff', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{user.name}</div>
            <div style={{ fontSize: 11, color: user.isMaster ? '#ffb4ab' : 'rgba(255,255,255,0.55)' }} className="mono">{user.badge}</div>
          </div>
          <div style={{
            width: 8, height: 8, borderRadius: 4,
            background: isOn ? '#22c55e' : 'rgba(255,255,255,0.25)',
            boxShadow: isOn ? '0 0 0 4px rgba(34,197,94,0.18)' : 'none',
            animation: isOn ? 'pulse-dot 1.6s ease-in-out infinite' : 'none',
          }} />
        </div>

        {/* Nav */}
        <nav style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          {tabs.map(t => {
            const on = tab === t.id;
            return (
              <button key={t.id} onClick={() => setTab(t.id)} style={{
                display: 'flex', alignItems: 'center', gap: 12,
                padding: '11px 14px',
                background: on ? 'rgba(229,91,19,0.18)' : 'transparent',
                color: on ? '#fff' : 'rgba(255,255,255,0.7)',
                border: 'none',
                borderLeft: on ? `3px solid var(--accent)` : '3px solid transparent',
                borderRadius: 8,
                cursor: 'pointer', textAlign: 'left',
                fontSize: 14, fontWeight: on ? 600 : 500,
                transition: 'all 120ms ease',
              }}>
                {t.icon}
                <span style={{ flex: 1 }}>{t.label}</span>
                {t.done && (
                  <span style={{
                    width: 16, height: 16, borderRadius: '50%', background: 'var(--good)',
                    display: 'grid', placeItems: 'center',
                  }}>
                    <IconCheck size={10} stroke={3} style={{ color: '#fff' }} />
                  </span>
                )}
              </button>
            );
          })}
        </nav>

        <div style={{ flex: 1 }} />

        {/* Day status panel */}
        <DayStatusFootblock />

        {/* Logout */}
        <button onClick={logout} style={{
          marginTop: 12, padding: '10px 12px',
          background: 'transparent', border: '1px solid rgba(255,255,255,0.1)',
          borderRadius: 10, color: 'rgba(255,255,255,0.7)',
          cursor: 'pointer', fontSize: 13, fontWeight: 500,
          display: 'flex', alignItems: 'center', gap: 8,
        }}>
          <IconLogout size={14} /> Sign out
        </button>
      </aside>

      {/* SCREEN */}
      <main style={{ display: 'flex', flexDirection: 'column', overflow: 'hidden', background: 'var(--paper)' }}>
        {tab === 'today'    && <ScreenToday    goTo={setTab} />}
        {tab === 'briefing' && <ScreenBriefing goTo={setTab} />}
        {tab === 'report'   && <ScreenReport   goTo={setTab} />}
        {tab === 'timecard' && <ScreenTimecard goTo={setTab} />}
      </main>
      </div>

      <AuditDrawer open={auditOpen} onClose={() => setAuditOpen(false)} trail={auditTrail} />
    </div>
  );
}

// ─── Master-mode banner ────────────────────────────────────────
function MasterBanner({ onOpen, count }) {
  return (
    <div style={{
      flexShrink: 0,
      background: 'repeating-linear-gradient(135deg, #b42318 0 12px, #8a1a12 12px 24px)',
      color: '#fff',
      padding: '8px 16px',
      display: 'flex', alignItems: 'center', gap: 14,
      fontSize: 12.5, fontWeight: 600,
      borderBottom: '2px solid #5a0e09',
      zIndex: 50,
    }}>
      <div style={{
        display: 'inline-flex', alignItems: 'center', gap: 6,
        background: 'rgba(0,0,0,0.35)', padding: '3px 9px', borderRadius: 4,
        fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: 1, textTransform: 'uppercase',
      }}>
        <IconShield size={12} /> MASTER ACCESS
      </div>
      <span style={{ flex: 1 }}>
        Diagnostic backdoor active · all actions are recorded and reported to the audit server.
      </span>
      <button onClick={onOpen} style={{
        background: 'rgba(255,255,255,0.18)',
        border: '1px solid rgba(255,255,255,0.32)',
        color: '#fff', padding: '4px 12px', borderRadius: 6,
        fontSize: 12, fontWeight: 600, cursor: 'pointer',
        display: 'inline-flex', alignItems: 'center', gap: 6,
        fontFamily: 'inherit',
      }}>
        <IconHistory size={12} /> View audit trail
        <span className="mono" style={{
          background: 'rgba(0,0,0,0.35)', padding: '1px 6px', borderRadius: 3,
          fontSize: 11, marginLeft: 4,
        }}>{count}</span>
      </button>
    </div>
  );
}

// ─── Audit drawer ──────────────────────────────────────────────
function AuditDrawer({ open, onClose, trail }) {
  if (!open) return null;
  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 200, animation: 'fade-in 180ms ease-out both' }}>
      <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.5)' }} />
      <div style={{
        position: 'absolute', right: 0, top: 0, bottom: 0,
        width: 480,
        background: 'var(--paper)',
        boxShadow: '-20px 0 60px rgba(0,0,0,0.4)',
        display: 'flex', flexDirection: 'column',
        animation: 'slide-up 280ms cubic-bezier(.2,.7,.2,1) both',
      }}>
        <div style={{
          padding: '16px 20px',
          borderBottom: '1px solid var(--line)',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          background: 'var(--panel)',
        }}>
          <div>
            <div className="eyebrow" style={{ color: 'var(--bad)' }}>MASTER ACCESS · AUDIT TRAIL</div>
            <div style={{ fontWeight: 700, fontSize: 18, marginTop: 2 }}>
              {trail.length} event{trail.length === 1 ? '' : 's'} this session
            </div>
          </div>
          <button onClick={onClose} style={{
            width: 32, height: 32, borderRadius: 16, border: 'none', background: '#EFF1F4',
            display: 'grid', placeItems: 'center', cursor: 'pointer',
          }}><IconClose size={16} /></button>
        </div>

        <div style={{ flex: 1, overflowY: 'auto', padding: 16 }}>
          {trail.length === 0 && (
            <Empty icon={<IconHistory size={28} />} title="No events yet" hint="All actions during this session will appear here." />
          )}
          {trail.map((e, i) => (
            <div key={e.id} style={{
              display: 'grid', gridTemplateColumns: '90px 1fr', gap: 12,
              padding: '10px 0',
              borderTop: i === 0 ? 'none' : '1px solid var(--line)',
            }}>
              <div>
                <div className="mono" style={{ fontSize: 11.5, fontWeight: 600 }}>
                  {new Date(e.ts).toLocaleTimeString('en-US', { hour12: false })}
                </div>
                <div className="mono" style={{ fontSize: 10, color: 'var(--muted-2)' }}>
                  {new Date(e.ts).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}
                </div>
              </div>
              <div>
                <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                  <span className="mono" style={{
                    fontSize: 10.5, fontWeight: 700, letterSpacing: 0.5,
                    padding: '2px 6px', borderRadius: 4,
                    background: e.event.startsWith('LOGIN') || e.event.startsWith('LOGOUT')
                      ? 'var(--bad-soft)' : 'var(--accent-soft)',
                    color: e.event.startsWith('LOGIN') || e.event.startsWith('LOGOUT')
                      ? 'var(--bad)' : 'var(--accent-deep)',
                  }}>{e.event}</span>
                </div>
                {e.detail && (
                  <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 4, lineHeight: 1.45 }}>
                    {e.detail}
                  </div>
                )}
              </div>
            </div>
          ))}
        </div>

        <div style={{
          padding: 14, borderTop: '1px solid var(--line)',
          background: 'var(--panel-2)',
          fontSize: 11.5, color: 'var(--muted)', lineHeight: 1.5,
        }}>
          <strong style={{ color: 'var(--bad)' }}>NOTE:</strong> This trail is read-only and tamper-evident.
          In production it is streamed to the audit server in real time.
        </div>
      </div>
    </div>
  );
}

// Small dark-theme version of the Mark text lockup for the sidebar
function BrandLockup() {
  const { tweaks } = useTweakValues();
  return (
    <div style={{ minWidth: 0 }}>
      <div style={{ fontSize: 14, fontWeight: 700, color: '#fff', letterSpacing: -0.2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
        {tweaks.companyName}
      </div>
      <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.5)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
        {tweaks.tagline}
      </div>
    </div>
  );
}

// Day status — live shift summary in the bottom of the sidebar
function DayStatusFootblock() {
  const { clockState, liveHrs, shift } = useApp();
  const isOn = clockState.status !== 'off';
  const ac = codeByValue(clockState.currentCode);
  return (
    <div style={{
      background: isOn ? 'rgba(34,197,94,0.08)' : 'rgba(255,255,255,0.04)',
      border: `1px solid ${isOn ? 'rgba(34,197,94,0.25)' : 'rgba(255,255,255,0.08)'}`,
      borderRadius: 12, padding: '12px 14px',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6 }}>
        <StatusDot tone={isOn ? 'good' : 'muted'} pulse={isOn} size={7} />
        <div className="eyebrow" style={{ color: 'rgba(255,255,255,0.6)', fontSize: 9.5 }}>
          {isOn ? 'ON SHIFT' : 'OFF DUTY'}
        </div>
      </div>
      {isOn ? (
        <>
          <div className="mono" style={{ fontSize: 22, fontWeight: 700, color: '#fff', letterSpacing: -0.5, lineHeight: 1 }}>
            {fmtClock(liveHrs)}
          </div>
          <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.55)', marginTop: 4 }}>
            <span className="mono">{ac?.code}</span> · {ac?.short || ac?.label}
          </div>
        </>
      ) : (
        <div style={{ fontSize: 12, color: 'rgba(255,255,255,0.55)', lineHeight: 1.4 }}>
          Ready to clock in.<br />Job: <span className="mono" style={{ color: '#fff' }}>{shift.projectNumber}</span>
        </div>
      )}
    </div>
  );
}

// ─── Boot ────────────────────────────────────────────────────
ReactDOM.createRoot(document.getElementById('root')).render(<App />);
