// Field-force dashboard — Persian RTL.
// Renders the action grid + status header inside an Android frame.

const { useState, useEffect } = React;

const ACTIONS = [
  { id: 'start',     label: 'شروع به کار',                  Icon: window.IconStart,         tone: 'primary' },
  { id: 'end',       label: 'پایان کار',                    Icon: window.IconEnd,           tone: 'danger'  },
  { id: 'calendar',  label: 'تقویم کاری',                   Icon: window.IconCalendarWork,  tone: 'neutral' },
  { id: 'break',     label: 'ثبت استراحت',                  Icon: window.IconBreak,         tone: 'neutral' },
  { id: 'holiday',   label: 'ثبت روز تعطیل',                Icon: window.IconHoliday,       tone: 'neutral' },
  { id: 'message',   label: 'ارسال پیام',                   Icon: window.IconMessage,       tone: 'neutral' },
  { id: 'register',  label: 'ثبت اطلاعات',                  Icon: window.IconRegister,      tone: 'neutral' },
  { id: 'samples',   label: 'ثبت تعداد سمپل دریافتی',        Icon: window.IconSamples,       tone: 'neutral' },
  { id: 'inventory', label: 'ثبت تعداد محصول موجود',         Icon: window.IconInventory,     tone: 'neutral' },
  { id: 'documents', label: 'آپلود مدارک',                    Icon: window.IconDocuments,     tone: 'neutral' },
  { id: 'earnings',  label: 'درآمد و حقوق',                    Icon: window.IconEarnings,      tone: 'neutral' },
];

const TONE_STYLES = {
  primary: { bg: 'var(--accent)',       fg: '#ffffff',          ring: 'transparent' },
  warning: { bg: 'var(--danger)',       fg: '#ffffff',          ring: 'transparent' },
  danger:  { bg: 'var(--surface)',      fg: 'var(--danger)',    ring: 'var(--danger)' },
  neutral: { bg: 'var(--surface)',      fg: 'var(--ink)',       ring: 'var(--border)' },
};

// ---------- atoms ----------
function StatusDot({ active }) {
  return (
    <span style={{
      width: 8, height: 8, borderRadius: 99,
      background: active ? 'var(--accent)' : 'var(--muted)',
      display: 'inline-block', boxShadow: active ? '0 0 0 3px color-mix(in oklab, var(--accent) 20%, transparent)' : 'none',
    }} />
  );
}

function Tile({ label, Icon, tone, onClick, subtitle, disabled, pulse }) {
  const t = TONE_STYLES[tone];
  const [pressed, setPressed] = useState(false);
  return (
    <button
      onClick={disabled ? undefined : onClick}
      onPointerDown={() => !disabled && setPressed(true)}
      onPointerUp={() => setPressed(false)}
      onPointerLeave={() => setPressed(false)}
      style={{
        all: 'unset', cursor: disabled ? 'default' : 'pointer', boxSizing: 'border-box',
        background: t.bg, color: t.fg,
        border: `1px solid ${t.ring}`,
        borderRadius: 18,
        padding: '14px 8px 12px',
        display: 'flex', flexDirection: 'column',
        alignItems: 'center', justifyContent: 'space-between',
        textAlign: 'center', minHeight: 112,
        opacity: disabled ? 0.55 : 1,
        transition: 'transform 120ms ease, box-shadow 200ms ease, background 200ms ease',
        transform: pressed ? 'scale(0.96)' : 'scale(1)',
        boxShadow: tone === 'primary'
          ? '0 6px 18px -8px color-mix(in oklab, var(--accent) 60%, transparent)'
          : tone === 'warning'
            ? '0 6px 18px -8px color-mix(in oklab, var(--danger) 60%, transparent)'
            : '0 1px 0 rgba(20,24,30,0.02)',
        animation: pulse ? 'ff-tile-pulse 1.6s ease-in-out infinite' : 'none',
      }}
    >
      <div style={{
        width: 44, height: 44, borderRadius: 12,
        background: tone === 'primary' || tone === 'warning'
          ? 'rgba(255,255,255,0.18)'
          : tone === 'danger'
            ? 'color-mix(in oklab, var(--danger) 8%, transparent)'
            : 'var(--icon-bg)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        marginTop: 4,
      }}>
        <Icon size={26} color={t.fg} />
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2 }}>
        <div style={{
          fontSize: 12.5, lineHeight: 1.3, fontWeight: 600,
          letterSpacing: '-0.01em', padding: '0 2px',
          textWrap: 'pretty',
        }}>{label}</div>
        {subtitle && (
          <div style={{
            fontSize: 10.5, fontWeight: 500,
            fontFamily: 'JetBrains Mono, ui-monospace, monospace',
            fontVariantNumeric: 'tabular-nums',
            color: tone === 'primary' || tone === 'warning' ? 'rgba(255,255,255,0.8)' : 'var(--muted)',
          }}>{subtitle}</div>
        )}
      </div>
    </button>
  );
}

// ---------- header ----------
function StatusHeader({ working, elapsed, onToggle, store }) {
  const app = window.useAppStore();
  const user = window.getUserById(app.session?.userId) || app.users[0];
  const hasStore = !!store;
  const mm = String(Math.floor(elapsed / 60)).padStart(2, '0');
  const ss = String(elapsed % 60).padStart(2, '0');
  const hh = String(Math.floor(elapsed / 3600)).padStart(2, '0');
  return (
    <div style={{
      padding: '14px 18px 18px',
      background: 'var(--bg)',
    }}>
      {/* top row */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        marginBottom: 14,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{
            width: 38, height: 38, borderRadius: 99,
            background: 'var(--surface)',
            border: '1px solid var(--border)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontWeight: 600, fontSize: 14, color: 'var(--ink)',
          }}>{user.initials}</div>
          <div style={{ lineHeight: 1.25 }}>
            <div style={{ fontSize: 11, color: 'var(--muted)' }}>۲ خرداد ۱۴۰۵</div>
            <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink)' }}>سلام {user.name}</div>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button style={{
            all: 'unset', cursor: 'pointer', position: 'relative',
            width: 38, height: 38, borderRadius: 99,
            background: 'var(--surface)', border: '1px solid var(--border)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: 'var(--ink)',
          }}>
            <window.IconBell size={18} />
            <span style={{
              position: 'absolute', top: 7, left: 9,
              width: 8, height: 8, borderRadius: 99,
              background: 'var(--danger)', border: '2px solid var(--surface)',
            }} />
          </button>
          <button
            onClick={() => window.appActions.logout()}
            title="خروج"
            style={{
              all: 'unset', cursor: 'pointer',
              width: 38, height: 38, borderRadius: 99,
              background: 'var(--surface)', border: '1px solid var(--border)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: 'var(--muted)',
            }}>
            <window.IconLogout size={16} />
          </button>
        </div>
      </div>

      {/* status card */}
      <div style={{
        background: working ? 'var(--ink)' : 'var(--surface)',
        color: working ? 'var(--bg)' : 'var(--ink)',
        border: working ? '1px solid var(--ink)' : '1px solid var(--border)',
        borderRadius: 18,
        padding: '14px 16px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          <div style={{
            fontSize: 11, fontWeight: 500,
            color: working ? 'rgba(255,255,255,0.55)' : 'var(--muted)',
            letterSpacing: '0.04em',
          }}>
            {working ? `در حال کار · ${store.name}` : hasStore ? `وضعیت روز · ${store.name}` : 'وضعیت روز'}
          </div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
            {working ? (
              <div style={{
                fontFamily: 'JetBrains Mono, ui-monospace, monospace',
                fontSize: 26, fontWeight: 500, letterSpacing: '-0.02em',
                fontVariantNumeric: 'tabular-nums',
              }}>{hh}:{mm}:{ss}</div>
            ) : hasStore ? (
              <div style={{ fontSize: 18, fontWeight: 600 }}>{store.name}</div>
            ) : (
              <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--muted)' }}>فروشگاهی برای امروز ندارید</div>
            )}
          </div>
        </div>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 8,
          padding: '6px 12px', borderRadius: 99,
          background: working ? 'color-mix(in oklab, var(--accent) 25%, transparent)' : 'var(--icon-bg)',
        }}>
          <StatusDot active={working} />
          <span style={{
            fontSize: 11, fontWeight: 600,
            color: working ? '#fff' : 'var(--ink)',
          }}>
            {working ? 'فعال' : hasStore ? 'آماده' : 'بدون فروشگاه'}
          </span>
        </div>
      </div>
    </div>
  );
}

// ---------- grid ----------
function ActionGrid({ items, onAction }) {
  return (
    <div style={{
      display: 'grid',
      gridTemplateColumns: 'repeat(3, 1fr)',
      gap: 10,
      padding: '4px 14px 16px',
    }}>
      {items.map(a => (
        <Tile key={a.id} {...a} onClick={() => onAction(a.id)} />
      ))}
    </div>
  );
}

// ---------- footer log ----------
function ActivityStrip({ entries }) {
  if (!entries.length) return null;
  return (
    <div style={{ padding: '0 18px 18px' }}>
      <div style={{
        fontSize: 11, color: 'var(--muted)', letterSpacing: '0.04em',
        marginBottom: 8, fontWeight: 500,
      }}>فعالیت اخیر</div>
      <div style={{
        background: 'var(--surface)', border: '1px solid var(--border)',
        borderRadius: 16, overflow: 'hidden',
      }}>
        {entries.slice(0, 3).map((e, i) => (
          <div key={i} style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: '11px 14px',
            borderTop: i ? '1px solid var(--border)' : 'none',
            fontSize: 13,
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <span style={{
                width: 6, height: 6, borderRadius: 99, background: 'var(--accent)',
              }} />
              <span style={{ color: 'var(--ink)' }}>{e.label}</span>
            </div>
            <span style={{
              fontSize: 11, color: 'var(--muted)',
              fontFamily: 'JetBrains Mono, ui-monospace, monospace',
              fontVariantNumeric: 'tabular-nums',
            }}>{e.time}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// ---------- main ----------
const todayKey = () => {
  const d = new Date();
  return `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`;
};

const loadBreakState = () => {
  try {
    const raw = localStorage.getItem('ff-break');
    if (!raw) return null;
    const parsed = JSON.parse(raw);
    if (parsed.day !== todayKey()) return null;
    return parsed;
  } catch { return null; }
};

function Dashboard({ breakThresholdSec = 3600 }) {
  const app = window.useAppStore();
  const [working, setWorking]   = useState(false);
  const [elapsed, setElapsed]   = useState(0);
  const [log, setLog]           = useState([]);
  const [view, setView]         = useState('home');
  const [sheetMode, setSheetMode] = useState(null);

  // break: { day, status: 'none'|'active'|'used', startedAt, alerted }
  const [breakState, setBreakState] = useState(
    () => loadBreakState() || { day: todayKey(), status: 'none', startedAt: null, alerted: false }
  );
  const [breakElapsed, setBreakElapsed] = useState(() => {
    const s = loadBreakState();
    if (s?.status === 'active') return Math.floor((Date.now() - s.startedAt) / 1000);
    return 0;
  });
  const [showBreakAlert, setShowBreakAlert] = useState(false);

  useEffect(() => {
    localStorage.setItem('ff-break', JSON.stringify(breakState));
  }, [breakState]);

  useEffect(() => {
    if (!working) return;
    const t = setInterval(() => setElapsed(e => e + 1), 1000);
    return () => clearInterval(t);
  }, [working]);

  // pull messages so the "ارسال پیام" tile can show an unread badge
  useEffect(() => { window.appActions.reloadMessages(); }, []);
  const unreadMessages = app.inbox.filter(m => !m.read).length;

  // today's assigned store (if any) — gates start/end/break actions
  const userId = app.session?.userId ?? app.currentUserId;
  const todayVisits = app.assignments[userId]?.[app.today] || [];
  const todayStore = todayVisits.length ? window.getStoreById(todayVisits[0].storeId) : null;
  const hasStore = !!todayStore;

  // live break timer + threshold alert
  useEffect(() => {
    if (breakState.status !== 'active') return;
    const tick = () => {
      const e = Math.floor((Date.now() - breakState.startedAt) / 1000);
      setBreakElapsed(e);
      if (e >= breakThresholdSec && !breakState.alerted) {
        setBreakState(s => ({ ...s, alerted: true }));
        setShowBreakAlert(true);
        pushLog('⚠ هشدار: استراحت طولانی · سرپرست مطلع شد');
      }
    };
    tick();
    const i = setInterval(tick, 1000);
    return () => clearInterval(i);
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [breakState.status, breakState.startedAt, breakThresholdSec, breakState.alerted]);

  // on mount, if break was already past threshold (e.g. reloaded), re-show alert
  useEffect(() => {
    if (breakState.status === 'active' && breakState.alerted) {
      setShowBreakAlert(true);
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const pushLog = (label) => {
    const now = new Date();
    const time = `${String(now.getHours()).padStart(2,'0')}:${String(now.getMinutes()).padStart(2,'0')}`;
    setLog(l => [{ label, time }, ...l]);
  };

  const startBreak = () => {
    window.appActions.recordBreak('start', 0, false);
    setBreakState({ day: todayKey(), status: 'active', startedAt: Date.now(), alerted: false });
    setBreakElapsed(0);
    pushLog('شروع استراحت');
  };
  const endBreak = () => {
    window.appActions.recordBreak('end', breakElapsed, breakElapsed >= breakThresholdSec);
    setBreakState(s => ({ ...s, status: 'used' }));
    setShowBreakAlert(false);
    pushLog('برگشت به کار از استراحت');
  };
  // dev helper: expose reset for tweak panel
  window.__resetBreak = () => {
    localStorage.removeItem('ff-break');
    setBreakState({ day: todayKey(), status: 'none', startedAt: null, alerted: false });
    setBreakElapsed(0);
    setShowBreakAlert(false);
  };

  const handleAction = (id) => {
    const action = ACTIONS.find(a => a.id === id);
    if (id === 'start')    { setSheetMode('start'); return; }
    if (id === 'end')      { setSheetMode('end');   return; }
    if (id === 'calendar') { setView('calendar');   return; }
    if (id === 'samples')  { setView('samples');    return; }
    if (id === 'inventory'){ setView('inventory');  return; }
    if (id === 'holiday')  { setView('holiday');    return; }
    if (id === 'message')  { setView('message');    return; }
    if (id === 'documents'){ setView('documents');  return; }
    if (id === 'earnings') { setView('earnings');   return; }
    if (id === 'break') {
      if (breakState.status === 'none')   { startBreak(); return; }
      if (breakState.status === 'active') { endBreak();   return; }
      return; // 'used' — disabled
    }
    pushLog(action.label);
  };

  const confirmSelfie = (file) => {
    if (sheetMode === 'start') {
      window.appActions.recordAttendance('start', file);
      setWorking(true); setElapsed(0);
      pushLog('شروع به کار · سلفی ثبت شد');
    } else if (sheetMode === 'end') {
      window.appActions.recordAttendance('end', file);
      setWorking(false);
      pushLog('پایان کار · سلفی ثبت شد');
    }
    setSheetMode(null);
  };

  // format break timer for tile subtitle
  const faNum = (n) => String(n).replace(/\d/g, d => '۰۱۲۳۴۵۶۷۸۹'[d]);
  const fmtBreak = (s) => {
    const h = Math.floor(s / 3600);
    const m = Math.floor((s % 3600) / 60);
    const ss = s % 60;
    if (h > 0) return `${faNum(String(h).padStart(2,'0'))}:${faNum(String(m).padStart(2,'0'))}:${faNum(String(ss).padStart(2,'0'))}`;
    return `${faNum(String(m).padStart(2,'0'))}:${faNum(String(ss).padStart(2,'0'))}`;
  };

  // build tile items with dynamic state
  const items = ACTIONS.map(a => {
    if (a.id === 'start') return { ...a, tone: working ? 'neutral' : 'primary', disabled: !hasStore };
    if (a.id === 'end')   return { ...a, tone: working ? 'danger'  : 'neutral', disabled: !hasStore };
    if (a.id === 'break') {
      if (!hasStore) {
        return { ...a, disabled: true };
      }
      if (breakState.status === 'active') {
        const over = breakElapsed >= breakThresholdSec;
        return {
          ...a,
          label: 'برگشت به کار',
          Icon: window.IconReturnToWork,
          tone: over ? 'warning' : 'primary',
          subtitle: fmtBreak(breakElapsed),
          pulse: over,
        };
      }
      if (breakState.status === 'used') {
        return { ...a, label: 'استراحت ثبت شد', disabled: true, subtitle: 'برای امروز' };
      }
    }
    if (a.id === 'message' && unreadMessages > 0) {
      return { ...a, subtitle: `${faNum(unreadMessages)} پیام جدید` };
    }
    return a;
  });

  if (view === 'calendar') {
    return <window.CalendarScreen onBack={() => setView('home')} />;
  }
  if (view === 'samples') {
    return (
      <window.SamplesScreen
        onBack={() => setView('home')}
        onSubmit={(counts, total, storeId) => {
          window.appActions.submitSamples(counts, storeId);
          pushLog(`ثبت سمپل دریافتی · ${total} عدد`);
          setView('home');
        }}
      />
    );
  }
  if (view === 'inventory') {
    return (
      <window.InventoryScreen
        onBack={() => setView('home')}
        onSubmit={(counts, total, storeId) => {
          window.appActions.submitInventory(counts, storeId);
          pushLog(`ثبت موجودی محصولات · ${total} عدد`);
          setView('home');
        }}
      />
    );
  }
  if (view === 'holiday') {
    return (
      <window.HolidayScreen
        onBack={() => setView('home')}
        onSubmit={(data) => {
          window.appActions.submitLeave(data);
          pushLog(`درخواست مرخصی · ${data.label}`);
          setView('home');
        }}
      />
    );
  }
  if (view === 'documents') {
    return (
      <window.DocumentsScreen
        onBack={() => setView('home')}
        onSubmit={(data) => {
          window.appActions.submitDocuments(data);
          pushLog('آپلود مدارک · در حال بررسی');
          setView('home');
        }}
      />
    );
  }
  if (view === 'earnings') {
    return <window.EarningsScreen onBack={() => setView('home')} />;
  }
  if (view === 'message') {
    return <window.MessagesScreen onBack={() => setView('home')} />;
  }

  return (
    <div style={{
      direction: 'rtl',
      background: 'var(--bg)',
      height: '100%',
      fontFamily: 'Vazirmatn, system-ui, sans-serif',
      color: 'var(--ink)',
      position: 'relative',
      display: 'flex',
      flexDirection: 'column',
      overflow: 'hidden',
    }}>
      <div style={{ flex: 1, overflowY: 'auto', minHeight: 0 }}>
        <StatusHeader working={working} elapsed={elapsed} onToggle={() => setWorking(!working)} store={todayStore} />
        <ActionGrid items={items} onAction={handleAction} />
        <ActivityStrip entries={log} />
      </div>
      <window.SelfieSheet
        open={sheetMode !== null}
        mode={sheetMode}
        onClose={() => setSheetMode(null)}
        onConfirm={confirmSelfie}
      />
      <window.BreakAlertModal
        open={showBreakAlert}
        elapsedSec={breakElapsed}
        onReturnToWork={() => { endBreak(); }}
        onDismiss={() => setShowBreakAlert(false)}
      />
      <style>{`
        @keyframes ff-tile-pulse {
          0%, 100% { box-shadow: 0 6px 18px -8px color-mix(in oklab, var(--danger) 60%, transparent); }
          50%      { box-shadow: 0 6px 24px -4px color-mix(in oklab, var(--danger) 90%, transparent); }
        }
      `}</style>
    </div>
  );
}

window.Dashboard = Dashboard;
