// App.jsx — Ana uygulama
const { useState, useEffect } = React;

function Clock({ lang }) {
  const [now, setNow] = useState(new Date());
  useEffect(() => { const id = setInterval(() => setNow(new Date()), 1000); return () => clearInterval(id); }, []);
  const locale = lang === 'tr' ? 'tr-TR' : 'en-GB';
  const timeStr = now.toLocaleTimeString(locale, { hour: '2-digit', minute: '2-digit', second: '2-digit' });
  const dateStr = now.toLocaleDateString(locale, { weekday: 'long', day: 'numeric', month: 'long' });
  return (
    <div style={{ textAlign: 'right' }}>
      <div style={{ fontSize: 26, fontWeight: 800, letterSpacing: '-0.02em', color: 'var(--text)', fontVariantNumeric: 'tabular-nums' }}>{timeStr}</div>
      <div style={{ fontSize: 12, color: 'var(--text-2)', fontWeight: 500, marginTop: 1 }}>{dateStr}</div>
    </div>
  );
}

function TableCard({ table, onClick }) {
  const [elapsed, setElapsed] = useState('');

  useEffect(() => {
    if (!table.occupied || !table.openedAt) return;
    const update = () => { setElapsed(window.elapsed(table.openedAt)); };
    update();
    const id = setInterval(update, 10000);
    return () => clearInterval(id);
  }, [table.openedAt, table.occupied]);

  const total = (table.orders || []).reduce((s, o) => s + o.price * o.qty, 0);

  return (
    <button onClick={onClick} className="table-card" style={{
      border: '2px solid',
      borderColor: table.occupied ? 'var(--accent)' : 'var(--green-border)',
      background: table.occupied ? 'white' : 'var(--green-bg)',
      borderRadius: 14, padding: '18px 16px', cursor: 'pointer',
      fontFamily: 'inherit', textAlign: 'left', transition: 'all 0.15s',
      boxShadow: table.occupied ? '0 2px 8px rgba(232,89,12,0.12)' : 'var(--shadow)',
      position: 'relative', minHeight: 120,
      display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
    }}
      onMouseEnter={e => { e.currentTarget.style.transform = 'translateY(-2px)'; e.currentTarget.style.boxShadow = table.occupied ? '0 6px 20px rgba(232,89,12,0.2)' : '0 4px 12px rgba(0,0,0,0.1)'; }}
      onMouseLeave={e => { e.currentTarget.style.transform = ''; e.currentTarget.style.boxShadow = table.occupied ? '0 2px 8px rgba(232,89,12,0.12)' : 'var(--shadow)'; }}
    >
      <div style={{ position: 'absolute', top: 10, right: 10 }}>
        <div style={{ width: 10, height: 10, borderRadius: '50%', background: table.occupied ? 'var(--accent)' : 'var(--green)', flexShrink: 0 }} />
      </div>

      <div>
        <div style={{ fontWeight: 800, fontSize: 17, color: 'var(--text)', marginBottom: 4 }}>{table.name}</div>
        {table.occupied ? (
          <div style={{ fontSize: 12, color: 'var(--text-2)', fontWeight: 500 }}>{table.waiter}</div>
        ) : (
          <div style={{ fontSize: 12, color: 'var(--green)', fontWeight: 600 }}>Boş</div>
        )}
      </div>

      {table.occupied && (
        <div>
          {(table.orders || []).length > 0 && (
            <div style={{ fontWeight: 800, fontSize: 18, color: 'var(--accent)', marginBottom: 2 }}>{fmt(total)}</div>
          )}
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <div style={{ fontSize: 11, color: 'var(--text-3)' }}>⏱ {elapsed}</div>
            <div style={{ fontSize: 11, color: 'var(--text-3)' }}>{(table.orders || []).length} ürün</div>
          </div>
        </div>
      )}
    </button>
  );
}

function App({ user: initialUser, onLogout }) {
  const [lang, setLang] = useState(Store.getSettings().lang);
  const [tables, setTables] = useState(Store.getTables());
  const [selectedTableId, setSelectedTableId] = useState(null);
  const [showAdmin, setShowAdmin] = useState(false);
  const [revenue, setRevenue] = useState(Store.getDailyRevenue());
  const [user, setUser] = useState(initialUser);

  const T = window.TRANS[lang];
  const isAdmin = user && user.role === 'admin';

  useEffect(() => {
    const onUpdate = () => {
      setTables(Store.getTables());
      setRevenue(Store.getDailyRevenue());
    };
    const onUnauth = () => onLogout();
    window.addEventListener('store-updated', onUpdate);
    window.addEventListener('store-unauth', onUnauth);
    return () => {
      window.removeEventListener('store-updated', onUpdate);
      window.removeEventListener('store-unauth', onUnauth);
    };
  }, []);

  const handleTableUpdate = (updatedTables) => {
    setTables(updatedTables);
    setRevenue(Store.getDailyRevenue());
  };

  const handleLangChange = async (l) => {
    await Store.setLang(l);
    setLang(l);
    if (showAdmin) { setShowAdmin(false); setTimeout(() => setShowAdmin(true), 50); }
  };

  const occupiedCount = tables.filter(t => t.occupied).length;
  const emptyCount = tables.length - occupiedCount;

  return (
    <div style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column' }}>

      <header className="app-header" style={{
        background: 'white', borderBottom: '1px solid var(--border)',
        padding: '0 28px', display: 'flex', alignItems: 'center', gap: 24,
        boxShadow: '0 1px 4px rgba(0,0,0,0.06)', flexShrink: 0, height: 72,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginRight: 8 }}>
          <div className="header-logo-box" style={{ width: 36, height: 36, background: 'var(--accent)', borderRadius: 10, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 20 }}>☕</div>
          <div>
            <div className="header-logo-name" style={{ fontWeight: 800, fontSize: 18, letterSpacing: '-0.02em' }}>adisyon</div>
            <div className="logo-sub" style={{ fontSize: 10, color: 'var(--text-3)', fontWeight: 500, marginTop: -2, letterSpacing: '0.05em', textTransform: 'uppercase' }}>kafe pos</div>
          </div>
        </div>

        <div className="header-pills" style={{ display: 'flex', gap: 8, marginRight: 'auto' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '6px 14px', borderRadius: 20, background: '#FFF3EE', border: '1px solid #FFD5BE' }}>
            <div style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--accent)' }} />
            <span style={{ fontSize: 13, fontWeight: 700, color: 'var(--accent)' }}>{occupiedCount} {T.occupiedTables}</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '6px 14px', borderRadius: 20, background: 'var(--green-bg)', border: '1px solid var(--green-border)' }}>
            <div style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--green)' }} />
            <span style={{ fontSize: 13, fontWeight: 700, color: 'var(--green)' }}>{emptyCount} {T.emptyTables}</span>
          </div>
        </div>

        <div className="header-revenue" style={{ textAlign: 'center', padding: '0 20px', borderLeft: '1px solid var(--border)', borderRight: '1px solid var(--border)' }}>
          <div className="header-revenue-label" style={{ fontSize: 11, color: 'var(--text-2)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 2 }}>{T.dailyRevenue}</div>
          <div className="header-revenue-value" style={{ fontSize: 22, fontWeight: 800, color: 'var(--accent)', letterSpacing: '-0.02em' }}>{fmt(revenue)}</div>
        </div>

        <div className="app-clock"><Clock lang={lang} /></div>

        <div className="header-buttons" style={{ display: 'flex', gap: 8, marginLeft: 8, alignItems: 'center' }}>
          <button onClick={() => { const l = lang === 'tr' ? 'en' : 'tr'; handleLangChange(l); }}
            style={{ padding: '8px 14px', borderRadius: 8, border: '1.5px solid var(--border)', background: 'white', cursor: 'pointer', fontFamily: 'inherit', fontSize: 13, fontWeight: 700, color: 'var(--text-2)' }}>
            {T.lang}
          </button>
          {isAdmin && (
            <button onClick={() => setShowAdmin(true)}
              style={{ padding: '8px 16px', borderRadius: 8, border: '1.5px solid var(--accent)', background: 'var(--accent-light)', cursor: 'pointer', fontFamily: 'inherit', fontSize: 13, fontWeight: 700, color: 'var(--accent)', display: 'flex', alignItems: 'center', gap: 6 }}>
              <span>⚙️</span><span className="admin-btn-label">{T.admin}</span>
            </button>
          )}
          <div className="header-user" style={{
            display: 'flex', alignItems: 'center', gap: 8,
            padding: '6px 10px 6px 12px', borderRadius: 20,
            background: isAdmin ? 'var(--accent-light)' : 'var(--green-bg)',
            border: isAdmin ? '1px solid #FFD5BE' : '1px solid var(--green-border)',
            flexShrink: 0,
          }}>
            <span className="header-user-icon" style={{ fontSize: 14 }} title={isAdmin ? 'Yönetici' : user.name}>
              {isAdmin ? '🔒' : '👤'}
            </span>
            <span className="header-user-name" style={{ fontSize: 13, fontWeight: 700, color: isAdmin ? 'var(--accent)' : 'var(--green)' }}>
              {isAdmin ? 'Yönetici' : user.name}
            </span>
            <button onClick={async () => { await Store.logout(); onLogout(); }}
              title="Çıkış"
              style={{
                width: 26, height: 26, borderRadius: 13, border: 'none', cursor: 'pointer',
                background: 'white', color: 'var(--text-2)', fontSize: 13,
                display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
              }}>⏻</button>
          </div>
        </div>
      </header>

      <main className="tables-main" style={{ flex: 1, padding: 28, overflowY: 'auto' }}>
        <div className="tables-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(160px, 1fr))', gap: 16, maxWidth: 1200 }}>
          {tables.map(table => (
            <TableCard key={table.id} table={table}
              onClick={() => setSelectedTableId(table.id)}
            />
          ))}
        </div>
      </main>

      {selectedTableId !== null && (
        <TableModal
          tableId={selectedTableId}
          tables={tables}
          lang={lang}
          user={user}
          onClose={() => setSelectedTableId(null)}
          onUpdate={(updated) => { handleTableUpdate(updated); }}
        />
      )}

      {showAdmin && isAdmin && (
        <AdminPanel
          lang={lang}
          onClose={() => setShowAdmin(false)}
          onLangChange={handleLangChange}
          currentUser={user}
        />
      )}
    </div>
  );
}

function Root() {
  // 'booting' | 'setup' | 'login' | 'app'
  const [phase, setPhase] = useState('booting');
  const [user, setUser] = useState(null);
  const [bootError, setBootError] = useState(null);

  useEffect(() => {
    (async () => {
      try {
        const status = await Store.checkSetup();
        if (status.needsSetup) {
          setPhase('setup');
          return;
        }
        const ok = await Store.init();
        if (ok) {
          setUser(Store.getUser());
          setPhase('app');
        } else {
          setPhase('login');
        }
      } catch (e) {
        setBootError(e.message || 'Bilinmeyen hata');
      }
    })();
  }, []);

  const handleAuthed = () => {
    setUser(Store.getUser());
    setPhase('app');
  };

  const handleLogout = () => {
    setUser(null);
    setPhase('login');
  };

  if (bootError) {
    return (
      <div style={{ padding: 40, textAlign: 'center', fontFamily: 'sans-serif' }}>
        <h2 style={{ color: '#DC2626' }}>Sunucuya bağlanılamadı</h2>
        <p style={{ color: '#6B6560', marginTop: 8 }}>{bootError}</p>
      </div>
    );
  }
  if (phase === 'booting') {
    return (
      <div className="splash">
        <div className="logo">☕</div>
        <div className="title">adisyon</div>
        <div className="sub">Yükleniyor…</div>
      </div>
    );
  }
  if (phase === 'setup') {
    return <SetupWizard onComplete={handleAuthed} />;
  }
  if (phase === 'login') {
    return <LoginScreen onLoggedIn={handleAuthed} />;
  }
  return <App user={user} onLogout={handleLogout} />;
}

ReactDOM.createRoot(document.getElementById('root')).render(<Root />);
