// admin-profiles.jsx

const AdminProfileCard = ({ profile: p, onEdit, onDelete }) => {
  const roi      = ((p.totalRevenue - p.totalInvested) / p.totalInvested);
  const cpl      = p.totalInvested / p.totalLeads;
  const convRate = (p.studentsConverted / p.totalLeads) * 100;

  const roiColor = roi >= 10 ? 'oklch(34% 0.13 150)' : roi >= 3 ? 'oklch(42% 0.14 75)' : 'oklch(48% 0.09 25)';
  const revenueColor = 'oklch(34% 0.13 150)';

  return (
    <div style={{ background: '#fff', borderRadius: 16, border: '1px solid oklch(90% 0.01 265)', padding: '24px', boxShadow: '0 2px 10px oklch(18% 0.06 265 / 0.05)' }}>
      {/* Header */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 18 }}>
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 5 }}>
            <div style={{ width: 9, height: 9, borderRadius: '50%', background: `oklch(58% 0.15 ${p.platformHue})`, flexShrink: 0 }} />
            <span style={{ fontSize: 11, fontWeight: 700, color: `oklch(38% 0.12 ${p.platformHue})`, letterSpacing: '0.06em', textTransform: 'uppercase' }}>{p.platform}</span>
          </div>
          <div style={{ fontWeight: 700, fontSize: 17, color: 'oklch(18% 0.03 265)', lineHeight: 1.2 }}>{p.instructor}</div>
          <div style={{ fontSize: 13, color: 'oklch(50% 0.05 265)', marginTop: 2 }}>{p.subject}</div>
        </div>
        <div style={{ textAlign: 'right', display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 10 }}>
          {p.rankPosition != null ? (
            <div>
              <div style={{ fontSize: 10, color: 'oklch(60% 0.03 265)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 1 }}>Rank</div>
              <div style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 28, fontWeight: 700, color: 'oklch(22% 0.06 265)', lineHeight: 1 }}>#{p.rankPosition}</div>
            </div>
          ) : (
            <span style={{ fontSize: 11, color: 'oklch(45% 0.08 265)', background: 'oklch(93% 0.03 265)', padding: '4px 10px', borderRadius: 20, fontWeight: 600 }}>Paid Ad</span>
          )}
          <div style={{ display: 'flex', gap: 6 }}>
            <button onClick={() => onEdit && onEdit(p)} title="Edit" style={iconBtn}>✎</button>
            <button onClick={() => onDelete && onDelete(p)} title="Delete" style={{ ...iconBtn, color: 'oklch(48% 0.16 25)' }}>×</button>
          </div>
        </div>
      </div>

      {/* Metric grid */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10, marginBottom: 16 }}>
        {[
          { label: 'Reviews',      value: p.totalReviews > 0 ? p.totalReviews : '—' },
          { label: 'Monthly Inv.', value: '$' + p.monthlyInvestment },
          { label: 'Total Invested', value: '$' + p.totalInvested.toLocaleString() },
          { label: 'Total Leads',  value: p.totalLeads },
          { label: 'Enrolled',     value: p.studentsConverted },
          { label: 'Conv. Rate',   value: convRate.toFixed(1) + '%' },
        ].map(m => (
          <div key={m.label} style={{ background: 'oklch(97.5% 0.006 60)', borderRadius: 10, padding: '11px 13px' }}>
            <div style={{ fontSize: 9, fontWeight: 700, color: 'oklch(55% 0.03 265)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 5 }}>{m.label}</div>
            <div style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 21, fontWeight: 700, color: 'oklch(22% 0.06 265)' }}>{m.value}</div>
          </div>
        ))}
      </div>

      {/* Revenue + ROI + CPL */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10, paddingTop: 14, borderTop: '1px solid oklch(93% 0.01 265)' }}>
        <div>
          <div style={{ fontSize: 9, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em', color: 'oklch(55% 0.03 265)', marginBottom: 4 }}>Revenue</div>
          <div style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 22, fontWeight: 700, color: revenueColor }}>${p.totalRevenue.toLocaleString()}</div>
        </div>
        <div>
          <div style={{ fontSize: 9, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em', color: 'oklch(55% 0.03 265)', marginBottom: 4 }}>ROI</div>
          <div style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 22, fontWeight: 700, color: roiColor }}>{roi.toFixed(1)}x</div>
        </div>
        <div>
          <div style={{ fontSize: 9, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em', color: 'oklch(55% 0.03 265)', marginBottom: 4 }}>Cost / Lead</div>
          <div style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 22, fontWeight: 700, color: 'oklch(30% 0.06 265)' }}>${cpl.toFixed(2)}</div>
        </div>
      </div>

      {/* Mini sparkline */}
      <div style={{ marginTop: 14, paddingTop: 14, borderTop: '1px solid oklch(93% 0.01 265)' }}>
        <div style={{ fontSize: 10, fontWeight: 700, color: 'oklch(55% 0.03 265)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 8 }}>Monthly Leads Trend</div>
        <svg width="100%" height={40} viewBox={`0 0 ${p.monthlyLeads.length * 30} 40`} preserveAspectRatio="none" style={{ display: 'block' }}>
          {(() => {
            const data = p.monthlyLeads;
            const max = Math.max(...data);
            const pts = data.map((v, i) => `${i * 30 + 15},${40 - Math.max(4, (v / max) * 36)}`).join(' ');
            return (
              <>
                <polyline points={pts} fill="none" stroke={`oklch(62% 0.12 ${p.platformHue})`} strokeWidth="2" strokeLinejoin="round" strokeLinecap="round" />
                {data.map((v, i) => (
                  <circle key={i} cx={i * 30 + 15} cy={40 - Math.max(4, (v / max) * 36)} r={3} fill={`oklch(62% 0.12 ${p.platformHue})`} />
                ))}
              </>
            );
          })()}
        </svg>
      </div>
    </div>
  );
};

const AdminProfiles = () => {
  const { profiles, loading } = window.useAdminData();
  const platforms = ['All', ...Array.from(new Set(profiles.map(p => p.platform)))];
  const [filter, setFilter] = React.useState('All');
  const [editing, setEditing] = React.useState(null); // null | 'new' | profile object

  const filtered = filter === 'All' ? profiles : profiles.filter(p => p.platform === filter);

  const handleDelete = async (p) => {
    if (!window.confirm(`Delete the ${p.platform} profile for ${p.instructor}? This also deletes its leads.`)) return;
    try { await window.ADMIN_DATA.deleteProfile(p.id); }
    catch (e) { alert('Delete failed: ' + e.message); }
  };

  const totals = {
    invested: profiles.reduce((s, p) => s + p.totalInvested, 0),
    leads:    profiles.reduce((s, p) => s + p.totalLeads, 0),
    revenue:  profiles.reduce((s, p) => s + p.totalRevenue, 0),
    converted: profiles.reduce((s, p) => s + p.studentsConverted, 0),
  };
  const totalRoi = ((totals.revenue - totals.invested) / totals.invested);

  return (
    <div>
      {/* Summary banner */}
      <div style={{ background: 'oklch(20% 0.07 265)', borderRadius: 14, padding: '20px 28px', marginBottom: 24, display: 'flex', gap: 0, alignItems: 'center', flexWrap: 'wrap' }}>
        {[
          { label: 'Active Profiles',  value: profiles.length },
          { label: 'Total Leads',      value: totals.leads.toLocaleString() },
          { label: 'Total Invested',   value: '$' + totals.invested.toLocaleString() },
          { label: 'Total Revenue',    value: '$' + totals.revenue.toLocaleString() },
          { label: 'Blended ROI',      value: totalRoi.toFixed(1) + 'x' },
          { label: 'Students Enrolled', value: totals.converted },
        ].map((s, i) => (
          <div key={s.label} style={{ flex: '1 1 0', minWidth: 120, padding: '0 20px', borderLeft: i > 0 ? '1px solid rgba(255,255,255,0.12)' : 'none' }}>
            <div style={{ fontSize: 10, color: 'rgba(255,255,255,0.48)', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 4 }}>{s.label}</div>
            <div style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 24, fontWeight: 700, color: '#fff' }}>{s.value}</div>
          </div>
        ))}
      </div>

      {/* Platform filter chips + Add */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 22, gap: 12, flexWrap: 'wrap' }}>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          {platforms.map(pl => {
            const active = filter === pl;
            return (
              <button key={pl} onClick={() => setFilter(pl)} style={{
                padding: '7px 16px', borderRadius: 20,
                border: '1.5px solid ' + (active ? 'oklch(22% 0.06 265)' : 'oklch(86% 0.02 265)'),
                background: active ? 'oklch(22% 0.06 265)' : '#fff',
                color: active ? '#fff' : 'oklch(42% 0.04 265)',
                fontSize: 13, fontWeight: 500, cursor: 'pointer',
                fontFamily: "'Plus Jakarta Sans', sans-serif",
                transition: 'all 0.15s',
              }}>{pl}</button>
            );
          })}
        </div>
        <button onClick={() => setEditing('new')} style={{
          background: 'oklch(22% 0.06 265)', color: '#fff', border: 'none',
          borderRadius: 10, padding: '9px 18px', fontWeight: 600, fontSize: 13, cursor: 'pointer',
          fontFamily: "'Plus Jakarta Sans', sans-serif",
        }}>+ Add profile</button>
      </div>

      {/* Profile cards grid */}
      {loading && profiles.length === 0 ? (
        <div style={{ padding: 40, color: 'oklch(50% 0.03 265)' }}>Loading…</div>
      ) : profiles.length === 0 ? (
        <div style={{ background: '#fff', borderRadius: 14, padding: 40, textAlign: 'center', color: 'oklch(50% 0.03 265)' }}>
          No profiles yet. Click <strong>+ Add profile</strong> to track your first platform listing.
        </div>
      ) : (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(380px, 1fr))', gap: 20 }}>
          {filtered.map(p => (
            <AdminProfileCard key={p.id} profile={p} onEdit={setEditing} onDelete={handleDelete} />
          ))}
        </div>
      )}

      {editing && (
        <AdminProfileFormModal
          profile={editing === 'new' ? null : editing}
          onClose={() => setEditing(null)}
        />
      )}
    </div>
  );
};

const AdminProfileFormModal = ({ profile, onClose }) => {
  const isEdit = !!profile;
  const [form, setForm] = React.useState({
    platform:           profile?.platform           || 'TakeLessons',
    platformShort:      profile?.platformShort      || 'TL',
    platformHue:        profile?.platformHue        || 220,
    instructor:         profile?.instructor         || '',
    subject:            profile?.subject            || '',
    rankPosition:       profile?.rankPosition ?? '',
    totalReviews:       profile?.totalReviews       || 0,
    monthlyInvestment:  profile?.monthlyInvestment  || 0,
    totalInvested:      profile?.totalInvested      || 0,
    totalLeads:         profile?.totalLeads         || 0,
    studentsConverted:  profile?.studentsConverted  || 0,
    avgStudentLTV:      profile?.avgStudentLTV      || 0,
    totalRevenue:       profile?.totalRevenue       || 0,
    status:             profile?.status             || 'active',
    monthlyLeads:       (profile?.monthlyLeads || [0,0,0,0,0,0,0,0]).join(','),
  });
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState(null);
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const submit = async (e) => {
    e.preventDefault();
    setError(null);
    if (!form.instructor.trim() || !form.subject.trim()) {
      setError('Instructor and subject are required.'); return;
    }
    const monthlyLeads = String(form.monthlyLeads).split(',').map(x => Number(x.trim()) || 0).slice(0, 8);
    while (monthlyLeads.length < 8) monthlyLeads.push(0);
    setBusy(true);
    try {
      if (isEdit) {
        await window.ADMIN_DATA.updateProfile(profile.id, { ...form, monthlyLeads });
      } else {
        await window.ADMIN_DATA.addProfile({ ...form, monthlyLeads });
      }
      onClose();
    } catch (err) {
      setError(err.message || 'Save failed.');
    } finally {
      setBusy(false);
    }
  };

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(15,20,40,0.6)', backdropFilter: 'blur(6px)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}>
      <div onClick={e => e.stopPropagation()} style={{ width: '100%', maxWidth: 640, background: '#fff', borderRadius: 18, padding: 28, boxShadow: '0 20px 60px rgba(0,0,0,0.25)', fontFamily: "'Plus Jakarta Sans', sans-serif", maxHeight: '90vh', overflowY: 'auto' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 18 }}>
          <h2 style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 26, fontWeight: 600, color: 'oklch(22% 0.06 265)' }}>
            {isEdit ? 'Edit profile' : 'New profile'}
          </h2>
          <button onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'oklch(55% 0.03 265)', fontSize: 24 }}>×</button>
        </div>
        <form onSubmit={submit}>
          <FieldRow>
            <FieldA label="Platform">
              <input value={form.platform} onChange={e => set('platform', e.target.value)} style={inA} required />
            </FieldA>
            <FieldA label="Short code (2-4 letters)">
              <input value={form.platformShort} onChange={e => set('platformShort', e.target.value.toUpperCase())} style={inA} maxLength={4} required />
            </FieldA>
            <FieldA label="Color hue (0–360)">
              <input type="number" min={0} max={360} value={form.platformHue} onChange={e => set('platformHue', Number(e.target.value))} style={inA} />
            </FieldA>
          </FieldRow>
          <FieldRow>
            <FieldA label="Instructor / Listing name">
              <input value={form.instructor} onChange={e => set('instructor', e.target.value)} style={inA} required />
            </FieldA>
            <FieldA label="Subject">
              <input value={form.subject} onChange={e => set('subject', e.target.value)} style={inA} required />
            </FieldA>
          </FieldRow>
          <FieldRow>
            <FieldA label="Rank position (blank for ads)">
              <input type="number" min={1} value={form.rankPosition} onChange={e => set('rankPosition', e.target.value)} style={inA} />
            </FieldA>
            <FieldA label="Total reviews">
              <input type="number" min={0} value={form.totalReviews} onChange={e => set('totalReviews', e.target.value)} style={inA} />
            </FieldA>
            <FieldA label="Status">
              <select value={form.status} onChange={e => set('status', e.target.value)} style={inA}>
                <option value="active">Active</option>
                <option value="paused">Paused</option>
                <option value="inactive">Inactive</option>
              </select>
            </FieldA>
          </FieldRow>
          <FieldRow>
            <FieldA label="Monthly investment ($)">
              <input type="number" min={0} value={form.monthlyInvestment} onChange={e => set('monthlyInvestment', e.target.value)} style={inA} />
            </FieldA>
            <FieldA label="Total invested ($)">
              <input type="number" min={0} value={form.totalInvested} onChange={e => set('totalInvested', e.target.value)} style={inA} />
            </FieldA>
          </FieldRow>
          <FieldRow>
            <FieldA label="Total leads">
              <input type="number" min={0} value={form.totalLeads} onChange={e => set('totalLeads', e.target.value)} style={inA} />
            </FieldA>
            <FieldA label="Students enrolled">
              <input type="number" min={0} value={form.studentsConverted} onChange={e => set('studentsConverted', e.target.value)} style={inA} />
            </FieldA>
            <FieldA label="Avg student LTV ($)">
              <input type="number" min={0} value={form.avgStudentLTV} onChange={e => set('avgStudentLTV', e.target.value)} style={inA} />
            </FieldA>
            <FieldA label="Total revenue ($)">
              <input type="number" min={0} value={form.totalRevenue} onChange={e => set('totalRevenue', e.target.value)} style={inA} />
            </FieldA>
          </FieldRow>
          <FieldA label="Monthly leads (8 numbers, comma-separated, oldest to newest)">
            <input value={form.monthlyLeads} onChange={e => set('monthlyLeads', e.target.value)} placeholder="11,13,14,15,14,16,17,18" style={inA} />
          </FieldA>
          {error && <div style={{ background: 'oklch(96% 0.03 25)', color: 'oklch(40% 0.15 25)', padding: '10px 14px', borderRadius: 8, fontSize: 13, marginTop: 8 }}>{error}</div>}
          <div style={{ display: 'flex', gap: 10, marginTop: 18 }}>
            <button type="button" onClick={onClose} style={{ flex: 1, background: 'transparent', color: 'oklch(22% 0.06 265)', border: '1.5px solid oklch(82% 0.04 265)', borderRadius: 10, padding: '12px 0', fontWeight: 600, fontSize: 14, cursor: 'pointer', fontFamily: "'Plus Jakarta Sans', sans-serif" }}>Cancel</button>
            <button type="submit" disabled={busy} style={{ flex: 2, background: 'oklch(22% 0.06 265)', color: '#fff', border: 'none', borderRadius: 10, padding: '12px 0', fontWeight: 700, fontSize: 14, cursor: busy ? 'wait' : 'pointer', opacity: busy ? 0.7 : 1, fontFamily: "'Plus Jakarta Sans', sans-serif" }}>{busy ? 'Saving…' : isEdit ? 'Save changes' : 'Create profile'}</button>
          </div>
        </form>
      </div>
    </div>
  );
};

const iconBtn = {
  background: 'oklch(96% 0.01 265)', border: 'none', borderRadius: 6,
  width: 28, height: 28, cursor: 'pointer', fontSize: 14,
  color: 'oklch(38% 0.04 265)', fontFamily: "'Plus Jakarta Sans', sans-serif",
  display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
};
const inA = {
  width: '100%', padding: '9px 12px', border: '1.5px solid oklch(88% 0.01 265)',
  borderRadius: 8, fontSize: 13, fontFamily: "'Plus Jakarta Sans', sans-serif",
  outline: 'none', background: '#fff',
};
const FieldA = ({ label, children }) => (
  <div style={{ marginBottom: 12, flex: 1, minWidth: 140 }}>
    <label style={{ display: 'block', fontSize: 11, fontWeight: 600, color: 'oklch(38% 0.04 265)', marginBottom: 4, letterSpacing: '0.02em' }}>{label}</label>
    {children}
  </div>
);
const FieldRow = ({ children }) => (
  <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>{children}</div>
);

Object.assign(window, { AdminProfiles });
