// Bleu SmartDER — App entry

const { useState, useEffect, useMemo } = React;

function App() {
  const auth = useAuth();
  const profile = auth?.profile;

  // role: 'admin' | 'tenant' — initialized from signed-in profile, then user-toggleable.
  const [role, setRole] = useState(profile?.role || 'admin');
  // route: 'a-overview', 'a-tenants', 'a-tenants/:id', 'a-devices', 'a-devices/:id', ...
  const [route, setRoute] = useState(profile?.role === 'tenant' ? 't-dashboard' : 'a-overview');
  // tenant context (when role=tenant)
  const [activeTenant, setActiveTenant] = useState(profile?.tenantId || 't-ahmed');

  // modal state
  const [addDevice, setAddDevice] = useState(null); // { tenantId } or null
  const [editDevice, setEditDevice] = useState(null);
  const [invoiceOpen, setInvoiceOpen] = useState(null);
  const [paymentInvoice, setPaymentInvoice] = useState(null);
  const [toast, setToast] = useState('');

  useEffect(() => {
    if (!toast) return;
    const t = setTimeout(() => setToast(''), 2400);
    return () => clearTimeout(t);
  }, [toast]);

  // When switching role, jump to the role's home
  useEffect(() => {
    setRoute(role === 'admin' ? 'a-overview' : 't-dashboard');
  }, [role]);

  const tenant = TENANTS.find(t => t.id === activeTenant);

  // crumbs
  const crumbs = useMemo(() => {
    if (role === 'admin') {
      if (route.startsWith('a-tenants/')) {
        const id = route.split('/')[1];
        const t = TENANTS.find(x => x.id === id);
        return ['Admin', 'Tenants', t?.name || ''];
      }
      if (route.startsWith('a-devices/')) {
        const id = route.split('/')[1];
        const d = DEVICES.find(x => x.id === id);
        return ['Admin', 'Devices', d?.label || ''];
      }
      const map = {
        'a-overview': ['Admin', 'Overview'],
        'a-tenants': ['Admin', 'Tenants'],
        'a-devices': ['Admin', 'Devices'],
        'a-invoices': ['Admin', 'Billing', 'All Invoices'],
        'a-verifications': ['Admin', 'Billing', 'Pending Verifications'],
        'a-packages': ['Admin', 'Packages & Tariff'],
        'a-settings': ['Admin', 'Settings'],
      };
      return map[route] || ['Admin'];
    } else {
      const map = {
        't-dashboard': [tenant?.name, 'Dashboard'],
        't-analytics': [tenant?.name, 'Analytics'],
        't-invoices': [tenant?.name, 'Billing', 'Invoices'],
        't-payments': [tenant?.name, 'Billing', 'Payment History'],
        't-account': [tenant?.name, 'My Account'],
      };
      return map[route] || [tenant?.name];
    }
  }, [role, route, tenant]);

  function nav(id) { setRoute(id); }

  function renderScreen() {
    if (role === 'admin') {
      if (route === 'a-overview') return <AdminOverview setRoute={setRoute} />;
      if (route === 'a-tenants') return <AdminTenants setRoute={setRoute} />;
      if (route.startsWith('a-tenants/')) {
        const id = route.split('/')[1];
        return <AdminTenantDetail tenantId={id} setRoute={setRoute}
          openAddDevice={(tid) => setAddDevice({ tenantId: tid })}
          openEditDevice={(did) => setEditDevice(did)} />;
      }
      if (route === 'a-devices') return <AdminDevices setRoute={setRoute} openAdd={() => setAddDevice({ tenantId: null })} />;
      if (route.startsWith('a-devices/')) {
        const id = route.split('/')[1];
        return <AdminDeviceDetail deviceId={id} setRoute={setRoute} />;
      }
      if (route === 'a-invoices') return <AdminInvoices setRoute={setRoute} />;
      if (route === 'a-verifications') return <AdminInvoices setRoute={setRoute} filterStatus="pending_verification" />;
      if (route === 'a-packages') return <AdminPackages />;
      if (route === 'a-settings') return <AdminSettings />;
    } else {
      if (route === 't-dashboard') return <TenantDashboard tenantId={activeTenant} setRoute={setRoute} />;
      if (route === 't-analytics') return <TenantAnalytics tenantId={activeTenant} />;
      if (route === 't-invoices') return <TenantInvoices tenantId={activeTenant} setRoute={setRoute} openInvoice={(id) => setInvoiceOpen(id)} />;
      if (route === 't-payments') return <TenantPayments tenantId={activeTenant} />;
      if (route === 't-account') return <TenantAccount tenantId={activeTenant} />;
    }
    return <div>Not implemented yet.</div>;
  }

  return (
    <div className="app">
      <Sidebar role={role} route={route} onNav={nav} tenant={tenant} />
      <div className="main">
        <Topbar
          role={role} setRole={setRole}
          activeTenant={activeTenant} setActiveTenant={setActiveTenant}
          crumbs={crumbs}
        />
        <div className="main-body">
          {renderScreen()}
        </div>
      </div>

      <DeviceFormModal
        open={!!addDevice}
        onClose={() => setAddDevice(null)}
        prefillTenant={addDevice?.tenantId}
        onSave={(status) => {
          setAddDevice(null);
          setToast(status === 'active'
            ? 'Device added & activated — telemetry simulator starting'
            : 'Device saved as draft');
        }}
      />

      <DeviceFormModal
        open={!!editDevice}
        onClose={() => setEditDevice(null)}
        editing={editDevice}
        onSave={() => { setEditDevice(null); setToast('Device updated'); }}
      />

      {invoiceOpen && (
        <TenantInvoiceDetail invoiceId={invoiceOpen}
          onClose={() => setInvoiceOpen(null)}
          onPay={() => { setPaymentInvoice(INVOICES.find(i => i.id === invoiceOpen)); setInvoiceOpen(null); }} />
      )}

      <PaymentModal
        open={!!paymentInvoice}
        onClose={() => setPaymentInvoice(null)}
        invoice={paymentInvoice}
        onSubmit={(method) => setToast(method === 'online' ? 'Payment received — invoice marked as paid' : 'Reference uploaded — pending admin verification')}
      />

      <Toast msg={toast} />
    </div>
  );
}

// Topbar — shared across all screens
const Topbar = ({ role, setRole, activeTenant, setActiveTenant, crumbs }) => {
  return (
    <div className="topbar">
      <div className="crumbs">
        {crumbs.filter(Boolean).map((c, i, a) => (
          <span key={i}>
            {i > 0 && <span style={{ margin: '0 8px', color: 'var(--ink-300)' }}>›</span>}
            {i === a.length - 1 ? <strong>{c}</strong> : c}
          </span>
        ))}
      </div>

      <div className="search">
        <Icon.Search size={14} />
        <input placeholder={role === 'admin' ? "Search tenants, devices, invoices…" : "Search devices, invoices…"} />
        <span className="mono" style={{ fontSize: 11, padding: '2px 6px', background: '#fff', border: '1px solid var(--line)', borderRadius: 4 }}>⌘K</span>
      </div>

      <div className="role-pill" title="Switch role (prototype)">
        <button data-on={role === 'admin'} onClick={() => setRole('admin')}>Super Admin</button>
        <button data-on={role === 'tenant'} onClick={() => setRole('tenant')}>Tenant</button>
      </div>

      {role === 'tenant' && (
        <div className="select" style={{ height: 36 }}>
          <Icon.Building size={14} />
          <select value={activeTenant} onChange={e => setActiveTenant(e.target.value)}>
            {TENANTS.map(t => <option key={t.id} value={t.id}>{t.name}</option>)}
          </select>
          <Icon.ChevronD size={14} />
        </div>
      )}

      <button className="topbtn" title="Notifications">
        <Icon.Bell size={16} />
        <span className="dot" />
      </button>

      <button className="topbtn" title="Help"><Icon.Help size={16} /></button>

      <Userchip role={role} activeTenant={activeTenant} />
    </div>
  );
};

const Userchip = ({ role, activeTenant }) => {
  const auth = useAuth();
  const initials = role === 'admin'
    ? (auth?.user?.email || 'BO').slice(0, 2).toUpperCase()
    : (TENANTS.find(t => t.id === activeTenant)?.contact.split(' ').map(x => x[0]).join('') || 'T');
  const displayName = role === 'admin'
    ? (auth?.profile?.name || 'Bleu Operator')
    : (TENANTS.find(t => t.id === activeTenant)?.contact || 'Tenant');
  return (
    <div className="userchip">
      <span className="av">{initials}</span>
      <div>
        <div className="who">{displayName}</div>
        <div className="role">{role === 'admin' ? 'Super Admin' : 'Tenant'}</div>
      </div>
      <button className="topbtn" title="Sign out" onClick={() => auth?.signOut?.()} style={{ marginInlineStart: 4 }}>
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
          <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/>
          <path d="M16 17l5-5-5-5"/>
          <path d="M21 12H9"/>
        </svg>
      </button>
    </div>
  );
};

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