const { useState: useStateA } = React;

const BarChart12 = ({ data }) => {
  const { labels, vals } = data;
  const w = 820, h = 240, pad = { l: 46, r: 16, t: 20, b: 32 };
  const max = Math.max(...vals) * 1.15;
  const innerW = w - pad.l - pad.r;
  const innerH = h - pad.t - pad.b;
  const barW = innerW / labels.length * 0.58;
  const gap = innerW / labels.length;
  return (
    <svg width="100%" viewBox={`0 0 ${w} ${h}`} style={{ maxWidth: '100%' }}>
      {[0, 0.25, 0.5, 0.75, 1].map((p, i) => (
        <g key={i}>
          <line x1={pad.l} x2={w - pad.r} y1={pad.t + innerH * (1 - p)} y2={pad.t + innerH * (1 - p)} stroke="var(--line)" strokeDasharray={p === 0 ? '' : '2 4'} />
          <text x={pad.l - 8} y={pad.t + innerH * (1 - p) + 3} textAnchor="end" fontSize="9.5" fill="var(--fg-3)" fontFamily="var(--mono)">{Math.round(max * p)}M</text>
        </g>
      ))}
      {vals.map((v, i) => {
        const x = pad.l + i * gap + (gap - barW) / 2;
        const barH = (v / max) * innerH;
        return (
          <g key={i}>
            <rect x={x} y={pad.t + innerH - barH} width={barW} height={barH} fill={i === vals.length - 1 ? 'var(--maroon)' : 'var(--fg)'} />
            <text x={x + barW / 2} y={h - 12} textAnchor="middle" fontSize="9.5" fill="var(--fg-3)" fontFamily="var(--mono)">{labels[i]}</text>
          </g>
        );
      })}
    </svg>
  );
};

const Analytics = () => {
  const a = window.__data.analytics;
  return (
    <div className="content view">
      <div className="section-head">
        <div>
          <div className="sub">Apr 20, 2026 · {window.__t('ana.rolling')}</div>
          <h2>{a.title}</h2>
        </div>
        <div className="pill-tabs">
          <button>{window.__t('ana.day')}</button>
          <button>{window.__t('ana.week')}</button>
          <button className="active">{window.__t('ana.month')}</button>
          <button>{window.__t('ana.quarter')}</button>
          <button>{window.__t('ana.year')}</button>
        </div>
      </div>

      <div className="metric-strip">
        {(a.kpis || []).map((m, i) => (
          <div className="m" key={i}>
            <div className="label">{m.label}</div>
            <div className="val">{i === 0 ? <em>{m.value}</em> : m.value}</div>
            <div className="delta" style={{ color: m.delta && m.delta.startsWith('−') && !m.delta.includes('أيام') && !m.delta.includes('d') ? 'var(--neg)' : 'var(--pos)' }}>{m.delta}</div>
          </div>
        ))}
      </div>

      <div className="grid cols-3" style={{ marginBottom: 22 }}>
        <div className="card">
          <div className="card-head">
            <div>
              <div className="sub">{a.sales.sub}</div>
              <h3>{a.sales.title}</h3>
            </div>
            <span className="tag pos">{a.sales.trendingUp}</span>
          </div>
          <div style={{ padding: 22 }}>
            <BarChart12 data={a.sales} />
          </div>
        </div>
        <div className="card">
          <div className="card-head">
            <div>
              <div className="sub">{a.sourcesSub}</div>
              <h3>{a.sourcesTitle}</h3>
            </div>
          </div>
          <div className="card-body">
            {a.sources.map((s, i) => (
              <div key={i} style={{ padding: '9px 0', borderBottom: i < a.sources.length - 1 ? '1px solid var(--line)' : 'none' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 7, fontSize: 13 }}>
                  <span>{s.name}</span>
                  <span className="mono" style={{ color: 'var(--maroon)', fontWeight: 500 }}>{s.pct}%</span>
                </div>
                <div style={{ height: 3, background: 'var(--bg-soft)' }}>
                  <div style={{ width: `${s.pct * 2.8}%`, height: '100%', background: i === 0 ? 'var(--maroon)' : 'var(--fg)' }} />
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="grid cols-2">
        <div className="card">
          <div className="card-head">
            <div>
              <div className="sub">{a.agentsSub}</div>
              <h3>{a.agentsTitle}</h3>
            </div>
            <button className="btn ghost">{a.hoodsFull}</button>
          </div>
          <div className="card-body flush">
            {a.agents.map((ag, i) => (
              <div key={i} style={{ padding: '16px 22px', borderBottom: i < a.agents.length - 1 ? '1px solid var(--line)' : 'none', display: 'grid', gridTemplateColumns: '34px 1fr 70px 100px 90px', gap: 14, alignItems: 'center' }}>
                <div className="avatar" style={{ width: 30, height: 30 }}>{ag.initials}</div>
                <div>
                  <div style={{ fontFamily: 'var(--serif)', fontSize: 15, fontWeight: 500, letterSpacing: '-0.005em' }}>{ag.name}</div>
                  <div className="mono" style={{ fontSize: 10, color: 'var(--fg-3)', textTransform: 'uppercase', letterSpacing: '0.1em', marginTop: 2 }}>#{String(i + 1).padStart(2, '0')} · {(ag.conv * 100).toFixed(0)}% conv</div>
                </div>
                <div className="mono" style={{ fontSize: 11.5, color: 'var(--fg-3)' }}>{ag.deals} deals</div>
                <div className="mono" style={{ fontSize: 12, textAlign: 'right', color: 'var(--fg)' }}>{ag.volume}</div>
                <div style={{ height: 4, background: 'var(--bg-soft)', position: 'relative' }}>
                  <div style={{ position: 'absolute', top: 0, left: 0, height: '100%', width: `${ag.conv * 250}%`, background: i === 0 ? 'var(--maroon)' : 'var(--fg)' }} />
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="card">
          <div className="card-head">
            <div>
              <div className="sub">{a.hoodsSub}</div>
              <h3>{a.hoodsTitle}</h3>
            </div>
          </div>
          <div className="card-body flush">
            {a.neighborhoods.map((n, i) => (
              <div key={i} style={{ padding: '16px 22px', borderBottom: i < a.neighborhoods.length - 1 ? '1px solid var(--line)' : 'none', display: 'grid', gridTemplateColumns: '1fr auto auto auto', gap: 18, alignItems: 'center' }}>
                <div style={{ fontFamily: 'var(--serif)', fontSize: 15, fontWeight: 500 }}>{n.name}</div>
                <div className="mono" style={{ fontSize: 11.5, color: 'var(--fg-3)' }}>{n.deals} deals</div>
                <div className="mono" style={{ fontSize: 12 }}>{n.volume}</div>
                <div className="mono" style={{ fontSize: 11, color: n.chg.startsWith('+') ? 'var(--pos)' : 'var(--neg)', fontWeight: 500 }}>{n.chg}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

const SETTINGS_STRINGS = {
  en: {
    org: 'Organization · Five Nodes Private Estates', title: 'Settings',
    profile: 'Profile & Account', appearance: 'Appearance', notifications: 'Notifications', team: 'Team & Roles', integrations: 'Integrations', billing: 'Billing', api: 'API & Data',
    fullName: 'Full name', fullNameDesc: 'Displayed on your profile and all outgoing communications.',
    jobTitle: 'Title', jobTitleDesc: 'Appears on signatures and reports.',
    email: 'Email', emailDesc: 'For login and critical alerts.',
    tz: 'Time zone', tzDesc: 'Schedules and reports use this zone.', tzAst: 'Arabia Standard Time (Doha)', tzGst: 'Gulf Standard Time (Dubai)', tzGmt: 'GMT (London)',
    theme: 'Theme', themeDesc: 'Switch between day and night mode. Syncs with the Tweaks panel.', day: 'Day', night: 'Night',
    tabular: 'Tabular numerics', tabularDesc: 'Align digits in tables and KPIs.',
    motion: 'Reduced motion', motionDesc: 'Disable subtle transitions.',
    notifItems: [
      { k: 'deal',   l: 'Deal closed',         d: 'Notify when any deal moves to closed status.' },
      { k: 'lead',   l: 'New qualified lead',  d: 'When an agent qualifies a lead above QAR 10M.' },
      { k: 'digest', l: 'Daily digest',        d: 'Morning summary of activity and schedule.' },
      { k: 'alerts', l: 'Market alerts',       d: 'Significant shifts in your focus districts.' },
    ],
    teamMembers: 'Team members', teamDesc: '18 seats · 15 active. Manage roles and access.', inviteMember: 'Invite member',
    connected: 'Connected · last synced 4 min ago', notConnected: 'Not connected', connect: 'Connect', manage: 'Manage',
    plan: 'Plan', planDesc: 'Enterprise · billed annually in QAR · renews Jan 1, 2027.', viewInvoices: 'View invoice history',
    apiAccess: 'API access', apiDesc: 'Programmatic access to your portfolio and pipeline data.', generateKey: 'Generate key',
  },
  ar: {
    org: 'المؤسسة · عقارات فايف نودز المميزة', title: 'الإعدادات',
    profile: 'الملف الشخصي والحساب', appearance: 'المظهر', notifications: 'الإشعارات', team: 'الفريق والأدوار', integrations: 'التكاملات', billing: 'الفواتير', api: 'API والبيانات',
    fullName: 'الاسم الكامل', fullNameDesc: 'يظهر في ملفك الشخصي وفي جميع المراسلات الصادرة.',
    jobTitle: 'المنصب', jobTitleDesc: 'يظهر في التواقيع والتقارير.',
    email: 'البريد الإلكتروني', emailDesc: 'لتسجيل الدخول والتنبيهات الهامة.',
    tz: 'المنطقة الزمنية', tzDesc: 'تستخدم الجداول والتقارير هذه المنطقة.', tzAst: 'توقيت شبه الجزيرة العربية (الدوحة)', tzGst: 'توقيت الخليج (دبي)', tzGmt: 'توقيت غرينيتش (لندن)',
    theme: 'المظهر', themeDesc: 'التبديل بين الوضع النهاري والليلي. يتزامن مع لوحة التعديلات.', day: 'نهار', night: 'ليل',
    tabular: 'أرقام جدولية', tabularDesc: 'محاذاة الأرقام في الجداول ومؤشرات الأداء.',
    motion: 'حركة مخفضة', motionDesc: 'تعطيل الانتقالات الدقيقة.',
    notifItems: [
      { k: 'deal',   l: 'صفقة مغلقة',             d: 'التنبيه عند انتقال أي صفقة إلى حالة الإغلاق.' },
      { k: 'lead',   l: 'عميل مؤهل جديد',         d: 'عندما يؤهل وكيل عميلاً بقيمة أكثر من 10 مليون ر.ق.' },
      { k: 'digest', l: 'ملخص يومي',              d: 'ملخص صباحي للنشاط والجدول.' },
      { k: 'alerts', l: 'تنبيهات السوق',          d: 'تحولات مهمة في مناطق تركيزك.' },
    ],
    teamMembers: 'أعضاء الفريق', teamDesc: '18 مقعد · 15 نشط. إدارة الأدوار والصلاحيات.', inviteMember: 'دعوة عضو',
    connected: 'متصل · آخر مزامنة قبل 4 دقائق', notConnected: 'غير متصل', connect: 'اتصال', manage: 'إدارة',
    plan: 'الخطة', planDesc: 'المؤسسة · تُفوتر سنوياً بالريال القطري · تُجدد 1 يناير 2027.', viewInvoices: 'عرض سجل الفواتير',
    apiAccess: 'الوصول عبر API', apiDesc: 'وصول برمجي إلى بيانات محفظتك وخط سيرك.', generateKey: 'إنشاء مفتاح',
  }
};

const Settings = ({ theme, setTheme }) => {
  const [section, setSection] = useStateA('profile');
  const [notif, setNotif] = useStateA({ deal: true, lead: true, digest: false, alerts: true });
  const s = SETTINGS_STRINGS[window.__lang === 'ar' ? 'ar' : 'en'];
  return (
    <div className="content view">
      <div className="section-head">
        <div>
          <div className="sub">{s.org}</div>
          <h2><em>{s.title}</em></h2>
        </div>
      </div>
      <div className="settings">
        <div className="settings-nav">
          {[
            { k: 'profile', l: s.profile },
            { k: 'appearance', l: s.appearance },
            { k: 'notifications', l: s.notifications },
            { k: 'team', l: s.team },
            { k: 'integrations', l: s.integrations },
            { k: 'billing', l: s.billing },
            { k: 'api', l: s.api },
          ].map(it => (
            <button key={it.k} className={section === it.k ? 'active' : ''} onClick={() => setSection(it.k)}>{it.l}</button>
          ))}
        </div>
        <div>
          {section === 'profile' && (
            <>
              <div className="setting-row">
                <div className="label"><h4>{s.fullName}</h4><p>{s.fullNameDesc}</p></div>
                <div className="control"><input type="text" defaultValue="Sultan" /></div>
              </div>
              <div className="setting-row">
                <div className="label"><h4>{s.jobTitle}</h4><p>{s.jobTitleDesc}</p></div>
                <div className="control"><input type="text" defaultValue="Chief Executive Officer" /></div>
              </div>
              <div className="setting-row">
                <div className="label"><h4>{s.email}</h4><p>{s.emailDesc}</p></div>
                <div className="control"><input type="email" defaultValue="sultan@almanara.qa" /></div>
              </div>
              <div className="setting-row">
                <div className="label"><h4>{s.tz}</h4><p>{s.tzDesc}</p></div>
                <div className="control">
                  <select defaultValue="AST">
                    <option value="AST">{s.tzAst}</option>
                    <option value="GST">{s.tzGst}</option>
                    <option value="GMT">{s.tzGmt}</option>
                  </select>
                </div>
              </div>
            </>
          )}
          {section === 'appearance' && (
            <>
              <div className="setting-row">
                <div className="label"><h4>{s.theme}</h4><p>{s.themeDesc}</p></div>
                <div className="control">
                  <div className="theme-picker">
                    <div className={`theme-tile ${theme === 'light' ? 'active' : ''}`} onClick={() => setTheme('light')}>
                      <span className="sw" style={{ background: '#efe8da' }} /> {s.day}
                    </div>
                    <div className={`theme-tile ${theme === 'dark' ? 'active' : ''}`} onClick={() => setTheme('dark')}>
                      <span className="sw" style={{ background: '#14110d' }} /> {s.night}
                    </div>
                  </div>
                </div>
              </div>
              <div className="setting-row">
                <div className="label"><h4>{s.tabular}</h4><p>{s.tabularDesc}</p></div>
                <div className="control"><div className="toggle on" /></div>
              </div>
              <div className="setting-row">
                <div className="label"><h4>{s.motion}</h4><p>{s.motionDesc}</p></div>
                <div className="control"><div className="toggle" /></div>
              </div>
            </>
          )}
          {section === 'notifications' && (
            <>
              {s.notifItems.map(n => (
                <div className="setting-row" key={n.k}>
                  <div className="label"><h4>{n.l}</h4><p>{n.d}</p></div>
                  <div className="control"><div className={`toggle ${notif[n.k] ? 'on' : ''}`} onClick={() => setNotif(x => ({ ...x, [n.k]: !x[n.k] }))} /></div>
                </div>
              ))}
            </>
          )}
          {section === 'team' && (
            <div className="setting-row">
              <div className="label"><h4>{s.teamMembers}</h4><p>{s.teamDesc}</p></div>
              <div className="control">
                <button className="btn primary" style={{ width: '100%', justifyContent: 'center' }}><Icon name="plus" size={13} /> {s.inviteMember}</button>
              </div>
            </div>
          )}
          {section === 'integrations' && (
            <>
              {['Qatar MLS', 'Property Finder Qatar', 'Hapondo', 'Saakin', 'QNB Payment Gateway'].map((n, i) => (
                <div className="setting-row" key={i}>
                  <div className="label"><h4>{n}</h4><p>{i === 4 ? s.notConnected : s.connected}</p></div>
                  <div className="control"><button className="btn">{i === 4 ? s.connect : s.manage}</button></div>
                </div>
              ))}
            </>
          )}
          {section === 'billing' && (
            <div className="setting-row">
              <div className="label"><h4>{s.plan}</h4><p>{s.planDesc}</p></div>
              <div className="control"><button className="btn">{s.viewInvoices}</button></div>
            </div>
          )}
          {section === 'api' && (
            <div className="setting-row">
              <div className="label"><h4>{s.apiAccess}</h4><p>{s.apiDesc}</p></div>
              <div className="control"><button className="btn">{s.generateKey}</button></div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

window.Analytics = Analytics;
window.Settings = Settings;
