// aerOS Superadmin — Organizations: list, create wizard, detail, actions, impersonate
const { useState: _oS } = React;

function vBadge(t, v) { return <Badge tone={v === 'hotel' ? 'info' : v === 'restaurant' ? 'warn' : 'brand'} size="sm">{t[v]}</Badge>; }
function planBadge(tier) {
  const map = { starter: 'neutral', basic: 'neutral', growth: 'brand', pro: 'brand', scale: 'info', enterprise: 'ok' };
  // Real plan name from the hydrated plan list; fallback to a capitalised slug.
  const plan = ((window.SA_DATA && window.SA_DATA.PLANS) || []).find(p => p.tier === tier);
  const label = (plan && plan.name) || (tier ? tier.charAt(0).toUpperCase() + tier.slice(1) : '—');
  return <Badge tone={map[tier] || 'neutral'} size="sm">{label}</Badge>;
}
function _lim(v) { return (v === -1 || v >= 9999) ? '∞' : v; }

/* ----------------------------- Org list ----------------------------- */
function SAOrgs({ t, orgs, setOrgs, onImpersonate, onCreate }) {
  const toast = useToast();
  const D = window.SA_DATA;
  const [detail, setDetail] = _oS(null);
  const [confirm, setConfirm] = _oS(null);
  const [menuFor, setMenuFor] = _oS(null);

  const doSuspendToggle = async (org) => {
    const next = !org.is_active;
    try {
      next ? await window.SA_API.activate(org.id) : await window.SA_API.suspend(org.id);
      setOrgs(os => os.map(o => o.id === org.id ? { ...o, is_active: next } : o));
      toast.ok(`${org.name} ${next ? t.active.toLowerCase() : t.suspended.toLowerCase()}.`, t.statusChanged);
    } catch (e) { toast.error(e.message || 'Hata', t.statusChanged); }
  };
  const doChangePlan = async (org, tier) => {
    const p = D.PLANS.find(p => p.tier === tier);
    try {
      await window.SA_API.changePlan(org.id, tier);
      setOrgs(os => os.map(o => o.id === org.id ? { ...o, plan_tier: tier, rooms_max: p ? p.maxRooms : o.rooms_max, products_max: p ? p.maxProducts : o.products_max } : o));
      toast.ok(`${org.name} → ${p ? p.name : tier}`, t.planChanged);
      setDetail(d => d && d.id === org.id ? { ...d, plan_tier: tier, rooms_max: p ? p.maxRooms : d.rooms_max, products_max: p ? p.maxProducts : d.products_max } : d);
    } catch (e) { toast.error(e.message || 'Hata', t.planChanged); }
  };

  const columns = [
    { key: 'name', label: t.name, sortable: true, render: o => (
      <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
        <Avatar name={o.name} size={32} square />
        <div style={{ minWidth: 0 }}>
          <div style={{ fontWeight: 600, whiteSpace: 'nowrap' }}>{o.name}</div>
          <div style={{ fontSize: 11.5, color: 'var(--fg-3)' }}>{o.slug}</div>
        </div>
      </div>
    ) },
    { key: 'vertical', label: t.vertical, sortable: true, render: o => vBadge(t, o.vertical) },
    { key: 'plan_tier', label: t.plan, sortable: true, render: o => planBadge(o.plan_tier) },
    { key: 'usage', label: t.usage, render: o => (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 4, minWidth: 110 }}>
        <Progress value={o.rooms_used} max={o.rooms_max} height={5} />
        <span style={{ fontSize: 11, color: 'var(--fg-3)' }} className="tnum">{o.rooms_used}/{_lim(o.rooms_max)} {t.rooms.toLowerCase()}</span>
      </div>
    ) },
    { key: 'monthly_orders', label: t.monthlyOrders, align: 'right', sortable: true, render: o => <span className="tnum">{o.monthly_orders.toLocaleString('tr-TR')}</span> },
    { key: 'is_active', label: t.status, sortable: true, sortValue: o => o.is_active ? 1 : 0, render: o => <Badge tone={o.is_active ? 'ok' : 'warn'} dot size="sm">{o.is_active ? t.active : t.suspended}</Badge> },
    { key: 'created_at', label: t.created, sortable: true, align: 'right', render: o => <span className="tnum" style={{ color: 'var(--fg-2)' }}>{o.created_at}</span> },
    { key: 'act', label: '', align: 'right', render: o => (
      <div style={{ position: 'relative' }}>
        <IconButton icon={Icon.dots} title={t.actions} onClick={(e) => { e.stopPropagation(); setMenuFor(menuFor === o.id ? null : o.id); }} active={menuFor === o.id} />
        {menuFor === o.id && (
          <>
            <div onClick={e => { e.stopPropagation(); setMenuFor(null); }} style={{ position: 'fixed', inset: 0, zIndex: 50 }} />
            <div onClick={e => e.stopPropagation()} style={{ position: 'absolute', right: 0, top: 38, zIndex: 51, background: 'var(--bg-0)', border: '1px solid var(--border)', borderRadius: 'var(--r-sm)', boxShadow: 'var(--shadow-lg)', padding: 5, minWidth: 184, textAlign: 'left' }}>
              <MenuItem icon={Icon.eye} label={t.viewDetail} onClick={() => { setDetail(o); setMenuFor(null); }} />
              <MenuItem icon={Icon.login} label={t.impersonate} onClick={() => { onImpersonate(o); setMenuFor(null); }} />
              <MenuItem icon={Icon.external} label={t.openMenu} onClick={() => { const h = location.hostname, p = location.port ? ':' + location.port : ''; window.open(location.protocol + '//' + o.slug + '.' + h + p + '/guest.html?mode=room&room=101', '_blank'); setMenuFor(null); }} />
              <div style={{ height: 1, background: 'var(--border)', margin: '5px 0' }} />
              {o.is_active
                ? <MenuItem icon={Icon.pause} label={t.suspend} tone="var(--warn)" onClick={() => { setConfirm({ org: o, type: 'suspend' }); setMenuFor(null); }} />
                : <MenuItem icon={Icon.play} label={t.activate} tone="var(--ok)" onClick={() => { setConfirm({ org: o, type: 'activate' }); setMenuFor(null); }} />}
            </div>
          </>
        )}
      </div>
    ) },
  ];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <Card noBody>
        <DataTable columns={columns} rows={orgs} searchKeys={['name', 'slug', 'city']} searchPlaceholder={t.searchOrg}
          pageSize={8} onRowClick={o => setDetail(o)}
          filters={[
            { key: 'vertical', label: t.vertical, options: [{ value: '', label: t.all + ' · ' + t.vertical }, { value: 'hotel', label: t.hotel }, { value: 'restaurant', label: t.restaurant }, { value: 'hospital', label: t.hospital }] },
            { key: 'plan_tier', label: t.plan, options: [{ value: '', label: t.all + ' · ' + t.plan }, ...D.PLANS.map(p => ({ value: p.tier, label: p.name }))] },
            { key: 'is_active', label: t.status, options: [{ value: '', label: t.all + ' · ' + t.status }, { value: 'true', label: t.active }, { value: 'false', label: t.suspended }] },
          ]}
          rightTools={<Button variant="primary" icon={Icon.plus} onClick={onCreate}>{t.createOrg}</Button>}
          initialSort={{ key: 'created_at', dir: 'desc' }}
        />
      </Card>

      <OrgDetailSheet t={t} org={detail} onClose={() => setDetail(null)} onChangePlan={doChangePlan} onToggle={(o) => setConfirm({ org: o, type: o.is_active ? 'suspend' : 'activate' })} onImpersonate={onImpersonate} />

      <ConfirmDialog open={!!confirm} onClose={() => setConfirm(null)}
        onConfirm={() => doSuspendToggle(confirm.org)}
        tone={confirm?.type === 'suspend' ? 'danger' : 'ok'}
        title={confirm?.type === 'suspend' ? t.suspendConfirm : t.activateConfirm}
        message={<><b>{confirm?.org.name}</b> {confirm?.type === 'suspend' ? t.suspendMsg : t.activateMsg}</>}
        confirmLabel={confirm?.type === 'suspend' ? t.suspend : t.activate} cancelLabel={t.cancel} />
    </div>
  );
}

function MenuItem({ icon, label, onClick, tone }) {
  const [h, setH] = _oS(false);
  return (
    <button onClick={onClick} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      style={{ display: 'flex', alignItems: 'center', gap: 9, width: '100%', padding: '8px 10px', borderRadius: 6, border: 'none', background: h ? 'var(--bg-2)' : 'transparent', color: tone || 'var(--fg-1)', fontSize: 13, fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left' }}>
      <span style={{ display: 'flex', color: tone || 'var(--fg-2)' }}>{icon({ size: 16 })}</span>{label}
    </button>
  );
}

/* ----------------------------- Org detail sheet ----------------------------- */
function OrgDetailSheet({ t, org, onClose, onChangePlan, onToggle, onImpersonate }) {
  const D = window.SA_DATA;
  if (!org) return null;
  return (
    <Sheet open={!!org} onClose={onClose} title={org.name} subtitle={`${org.slug} · ${org.city}`} width={480}
      footer={<>
        <Button variant={org.is_active ? 'dangerSoft' : 'secondary'} icon={org.is_active ? Icon.pause : Icon.play} onClick={() => onToggle(org)}>{org.is_active ? t.suspend : t.activate}</Button>
        <Button variant="primary" icon={Icon.login} onClick={() => { onImpersonate(org); onClose(); }}>{t.impersonate}</Button>
      </>}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <Avatar name={org.name} size={52} square />
          <div style={{ flex: 1 }}>
            <div style={{ display: 'flex', gap: 6, marginBottom: 6 }}>{vBadge(t, org.vertical)}{planBadge(org.plan_tier)}<Badge tone={org.is_active ? 'ok' : 'warn'} dot size="sm">{org.is_active ? t.active : t.suspended}</Badge></div>
            <div style={{ fontSize: 12, color: 'var(--fg-3)' }} className="tnum">{t.created}: {org.created_at}</div>
          </div>
        </div>

        <Grid cols={3} gap={12}>
          <MiniStat label={t.monthlyOrders} value={org.monthly_orders.toLocaleString('tr-TR')} />
          <MiniStat label={t.monthlyRevenue} value={fmtTRY(org.monthly_revenue)} />
          <MiniStat label={t.avgBasket} value={fmtTRY(org.avg_basket)} />
        </Grid>

        <div>
          <SecLabel>{t.usage} · {t.limits}</SecLabel>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14, marginTop: 10 }}>
            <Progress label={t.rooms} value={org.rooms_used} max={org.rooms_max} />
            <Progress label={t.products} value={org.products_used} max={org.products_max} />
          </div>
        </div>

        <div>
          <SecLabel>{t.changePlan}</SecLabel>
          <div style={{ marginTop: 10 }}>
            <Select value={org.plan_tier} onChange={v => onChangePlan(org, v)} options={D.PLANS.map(p => ({ value: p.tier, label: `${p.name} · ${t.maxRooms} ${p.maxRooms} · ${t.maxProducts} ${p.maxProducts}` }))} />
          </div>
        </div>

        <div>
          <SecLabel>{t.ordersTrend} · {t.last12}</SecLabel>
          <div style={{ marginTop: 10, background: 'var(--bg-2)', borderRadius: 'var(--r-sm)', padding: '12px 14px' }}>
            <LineChart data={org.spark} height={120} showDots={false} valueFmt={v => v} color="var(--brand)" />
          </div>
        </div>
      </div>
    </Sheet>
  );
}

function MiniStat({ label, value }) {
  return (
    <div style={{ background: 'var(--bg-2)', borderRadius: 'var(--r-sm)', padding: '11px 12px' }}>
      <div style={{ fontSize: 10.5, color: 'var(--fg-3)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.04em', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{label}</div>
      <div className="tnum" style={{ fontSize: 16, fontWeight: 700, marginTop: 4 }}>{value}</div>
    </div>
  );
}
function SecLabel({ children }) { return <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--fg-2)', textTransform: 'uppercase', letterSpacing: '0.05em' }}>{children}</div>; }

/* ----------------------------- Create wizard ----------------------------- */
function SACreateOrg({ t, open, onClose, onCreated }) {
  const toast = useToast();
  const D = window.SA_DATA;
  const [step, setStep] = _oS(0);
  const blank = { name: '', slug: '', vertical: 'hotel', plan: 'pro', currency: '₺', lang: 'tr', color: '#6E9F2A', adminLogin: '', adminMail: '', adminPass: '' };
  const [f, setF] = _oS(blank);
  const set = (k, v) => setF(s => ({ ...s, [k]: v }));
  const autoSlug = (name) => name.toLowerCase().replace(/ı/g, 'i').replace(/ş/g, 's').replace(/ğ/g, 'g').replace(/ü/g, 'u').replace(/ö/g, 'o').replace(/ç/g, 'c').replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
  const steps = [t.step_org, t.step_brand, t.step_admin];
  const canNext = step === 0 ? f.name && f.slug : step === 1 ? true : f.adminLogin && f.adminMail && f.adminPass;
  const reset = () => { setStep(0); setF(blank); };
  const submit = () => {
    onCreated(f);
    toast.ok(`${f.name} ${t.orgCreatedMsg}`, t.orgCreated);
    reset(); onClose();
  };
  const colors = ['#6E9F2A', '#2563eb', '#0d9488', '#b45309', '#7c3aed', '#be123c', '#0891b2', '#334155'];

  return (
    <Modal open={open} onClose={() => { onClose(); }} title={t.createTitle} subtitle={t.createSub} icon={Icon.building} width={620}
      footer={<>
        {step > 0 && <Button variant="ghost" icon={Icon.arrowLeft} onClick={() => setStep(s => s - 1)}>{t.back}</Button>}
        <div style={{ flex: 1 }} />
        <Button variant="ghost" onClick={onClose}>{t.cancel}</Button>
        {step < 2
          ? <Button variant="primary" iconRight={Icon.arrowRight} disabled={!canNext} onClick={() => setStep(s => s + 1)}>{t.next}</Button>
          : <Button variant="primary" icon={Icon.check} disabled={!canNext} onClick={submit}>{t.create}</Button>}
      </>}>
      {/* stepper */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 0, marginBottom: 24 }}>
        {steps.map((s, i) => (
          <React.Fragment key={i}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
              <div style={{ width: 26, height: 26, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12.5, fontWeight: 700, background: i <= step ? 'var(--brand)' : 'var(--bg-3)', color: i <= step ? 'var(--on-brand)' : 'var(--fg-3)' }}>{i < step ? Icon.check({ size: 14 }) : i + 1}</div>
              <span style={{ fontSize: 13, fontWeight: i === step ? 600 : 500, color: i <= step ? 'var(--fg-1)' : 'var(--fg-3)' }}>{s}</span>
            </div>
            {i < 2 && <div style={{ flex: 1, height: 2, background: i < step ? 'var(--brand)' : 'var(--border)', margin: '0 12px' }} />}
          </React.Fragment>
        ))}
      </div>

      {step === 0 && (
        <Grid cols={2} gap={16}>
          <Field label={t.orgName} required span={2}><Input value={f.name} onChange={v => { set('name', v); if (!f._slugTouched) { const s = autoSlug(v); set('slug', s); if (!f._adminTouched) { set('adminLogin', s ? s + '-admin' : ''); set('adminMail', s ? 'admin@' + s + '.com' : ''); } } }} placeholder="Radisson Collection Vadistanbul" /></Field>
          <Field label={t.orgSlug} required hint={t.slugHint} span={2}><Input value={f.slug} onChange={v => { const s = autoSlug(v); set('slug', s); set('_slugTouched', true); if (!f._adminTouched) { set('adminLogin', s ? s + '-admin' : ''); set('adminMail', s ? 'admin@' + s + '.com' : ''); } }} suffix=".qrmenu.boranyazilim.com" /></Field>
          <Field label={t.vertical} required><Select value={f.vertical} onChange={v => set('vertical', v)} options={[{ value: 'hotel', label: t.hotel }, { value: 'restaurant', label: t.restaurant }, { value: 'hospital', label: t.hospital }]} /></Field>
          <Field label={t.planTier} required><Select value={f.plan} onChange={v => set('plan', v)} options={D.PLANS.map(p => ({ value: p.tier, label: `${p.name}${p.price ? ' · €' + Number(p.price).toLocaleString('de-DE') + '/ay' : ''}` }))} /></Field>
        </Grid>
      )}
      {step === 1 && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <Grid cols={2} gap={16}>
            <Field label={t.defaultCurrency}><Select value={f.currency} onChange={v => set('currency', v)} options={[{ value: '₺', label: '₺ TRY' }, { value: '€', label: '€ EUR' }, { value: '$', label: '$ USD' }, { value: '£', label: '£ GBP' }]} /></Field>
            <Field label={t.defaultLang}><Select value={f.lang} onChange={v => set('lang', v)} options={[{ value: 'tr', label: 'Türkçe' }, { value: 'en', label: 'English' }, { value: 'de', label: 'Deutsch' }, { value: 'ar', label: 'العربية' }]} /></Field>
          </Grid>
          <Field label={t.primaryColor}>
            <div style={{ display: 'flex', gap: 9, flexWrap: 'wrap', alignItems: 'center' }}>
              {colors.map(c => (
                <button key={c} onClick={() => set('color', c)} style={{ width: 34, height: 34, borderRadius: 9, background: c, border: f.color === c ? '2px solid var(--fg-1)' : '2px solid transparent', cursor: 'pointer', transform: f.color === c ? 'scale(1.08)' : 'none', transition: 'all 120ms' }} />
              ))}
            </div>
          </Field>
          {/* live brand preview */}
          <div>
            <SecLabel>Önizleme</SecLabel>
            <div style={{ marginTop: 10, border: '1px solid var(--border)', borderRadius: 'var(--r-md)', overflow: 'hidden' }}>
              <div style={{ height: 56, background: f.color, display: 'flex', alignItems: 'center', gap: 12, padding: '0 16px' }}>
                <div style={{ width: 34, height: 34, borderRadius: 8, background: 'rgba(255,255,255,0.25)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700 }}>{(f.name || 'A')[0]}</div>
                <div style={{ color: '#fff', fontWeight: 700, fontSize: 15 }}>{f.name || t.orgName}</div>
              </div>
              <div style={{ padding: 14, display: 'flex', gap: 8, background: 'var(--bg-0)' }}>
                <span style={{ padding: '7px 14px', borderRadius: 8, background: f.color, color: '#fff', fontSize: 13, fontWeight: 600 }}>Sipariş ver</span>
                <span style={{ padding: '7px 14px', borderRadius: 8, border: `1px solid ${f.color}`, color: f.color, fontSize: 13, fontWeight: 600 }}>Menü</span>
              </div>
            </div>
          </div>
        </div>
      )}
      {step === 2 && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div style={{ display: 'flex', gap: 10, padding: '11px 13px', background: 'var(--info-soft)', borderRadius: 'var(--r-sm)', color: 'var(--info)', fontSize: 12.5 }}>
            {Icon.info({ size: 16 })}<span>İlk yönetici hesabı oluşturulacak ve giriş bilgileri e-posta ile gönderilecek.</span>
          </div>
          <Grid cols={2} gap={16}>
            <Field label={t.adminLogin} required><Input value={f.adminLogin} onChange={v => { set('adminLogin', v); set('_adminTouched', true); }} placeholder={(f.slug || 'otel') + '-admin'} icon={Icon.user} /></Field>
            <Field label={t.adminMail} required><Input value={f.adminMail} onChange={v => set('adminMail', v)} type="email" placeholder="admin@otel.com" /></Field>
            <Field label={t.adminPass} required span={2}><Input value={f.adminPass} onChange={v => set('adminPass', v)} type="password" icon={Icon.shield} /></Field>
          </Grid>
        </div>
      )}
    </Modal>
  );
}

Object.assign(window, { SAOrgs, SACreateOrg });
