// Clientelle hero video — CRM app UI (views, overlays, cursor)
// Pure presentational; driven by a derived-state object `d` from the director.
// Uses page CSS vars: --accent, --accent-soft, --ink, --surface, --line

const CRM = {
  ink: 'var(--ink)',
  soft: 'var(--ink-soft)',
  line: 'var(--line)',
  surface: '#FFFDFB',
  wash: '#F6F1EA',
  accent: 'var(--accent)',
  accentSoft: 'var(--accent-soft)',
  lilac: 'oklch(58% 0.10 320)',
  green: 'oklch(58% 0.10 155)',
  sans: "'Instrument Sans', system-ui, sans-serif",
  serif: "'Instrument Serif', serif",
  mono: "'JetBrains Mono', ui-monospace, monospace",
};

const crmStripe = {
  background: 'repeating-linear-gradient(135deg, #EFE9E0 0 10px, #E4DCD0 10px 20px)',
};

function CrmChip({ children, tone = 'rose' }) {
  const bg = tone === 'rose' ? 'var(--accent-soft)' : tone === 'lilac' ? 'oklch(95% 0.03 320)' : 'rgba(42,33,38,0.06)';
  const fg = tone === 'rose' ? 'var(--accent)' : tone === 'lilac' ? CRM.lilac : CRM.soft;
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', padding: '5px 12px', borderRadius: 999,
      background: bg, color: fg, fontSize: 13, fontWeight: 600, fontFamily: CRM.sans,
    }}>{children}</span>
  );
}

function CrmCard({ x, y, w, h, title, children, pad = 24 }) {
  return (
    <div style={{
      position: 'absolute', left: x, top: y, width: w, height: h,
      background: CRM.surface, border: `1px solid ${CRM.line}`, borderRadius: 14,
      padding: pad, boxSizing: 'border-box', fontFamily: CRM.sans,
    }}>
      {title && <div style={{ fontSize: 13, letterSpacing: '0.08em', textTransform: 'uppercase', color: CRM.soft, fontWeight: 600, marginBottom: 16 }}>{title}</div>}
      {children}
    </div>
  );
}

// ── Sidebar + chrome ────────────────────────────────────────────────────────
function CrmShell({ view, children }) {
  const items = ['Dashboard', 'Clients', 'Leads', 'Gallery', 'Money', 'Content', 'Reviews', 'Tasks'];
  const activeIdx = view === 'clients' ? 1 : view === 'gallery' ? 3 : 0;
  return (
    <div style={{ position: 'absolute', inset: 0, background: '#FBF8F4', fontFamily: CRM.sans, color: CRM.ink }}>
      {/* top bar */}
      <div style={{ position: 'absolute', left: 0, top: 0, right: 0, height: 56, borderBottom: `1px solid ${CRM.line}`, background: CRM.surface, display: 'flex', alignItems: 'center', padding: '0 20px', boxSizing: 'border-box' }}>
        <div style={{ display: 'flex', gap: 8 }}>
          <div style={{ width: 12, height: 12, borderRadius: '50%', background: '#E0635A' }}></div>
          <div style={{ width: 12, height: 12, borderRadius: '50%', background: '#E2A93B' }}></div>
          <div style={{ width: 12, height: 12, borderRadius: '50%', background: '#5FB36A' }}></div>
        </div>
        <div style={{ position: 'absolute', left: '50%', transform: 'translateX(-50%)', padding: '6px 22px', borderRadius: 8, background: 'rgba(42,33,38,0.05)', fontFamily: CRM.mono, fontSize: 13, color: CRM.soft }}>
          maya.zivo.app
        </div>
      </div>
      {/* sidebar */}
      <div style={{ position: 'absolute', left: 0, top: 56, bottom: 0, width: 240, borderRight: `1px solid ${CRM.line}`, background: CRM.surface, boxSizing: 'border-box', padding: '0 16px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '24px 12px 20px' }}>
          <div style={{ width: 26, height: 26, borderRadius: 8, background: 'var(--accent)' }}></div>
          <div style={{ fontFamily: CRM.serif, fontSize: 20 }}>Maya&rsquo;s Studio</div>
        </div>
        {items.map((it, i) => {
          const active = i === activeIdx;
          return (
            <div key={it} style={{
              position: 'absolute', left: 16, width: 208, top: 120 + i * 50 - 56, height: 44,
              display: 'flex', alignItems: 'center', padding: '0 14px', boxSizing: 'border-box',
              borderRadius: 10, fontSize: 16, fontWeight: active ? 600 : 500,
              background: active ? 'var(--accent-soft)' : 'transparent',
              color: active ? 'var(--accent)' : CRM.soft,
              transition: 'background 200ms, color 200ms',
            }}>{it}</div>
          );
        })}
      </div>
      {/* main */}
      <div style={{ position: 'absolute', left: 240, top: 56, right: 0, bottom: 0 }}>
        {children}
      </div>
    </div>
  );
}

// NOTE: children of CrmShell are positioned in CANVAS coords minus (240, 56).
const MX = (x) => x - 240;
const MY = (y) => y - 56;

// ── Dashboard view ──────────────────────────────────────────────────────────
function CrmDashboard({ d }) {
  const money = Math.round(d.moneyCount);
  const stats = [
    { label: 'Today', value: d.newBookingP > 0.5 ? '4 bookings' : '3 bookings' },
    { label: 'This month', value: '$' + money.toLocaleString() },
    { label: 'Leads waiting', value: '2' },
  ];
  const todayRows = [
    ['9:00', 'Lena R.', 'Classic fill'],
    ['11:30', 'Priya S.', 'Volume full set'],
    ['1:00', 'Walk-in', 'Consult'],
  ];
  return (
    <div style={{ position: 'absolute', inset: 0 }}>
      <div style={{ position: 'absolute', left: MX(288), top: MY(96), fontFamily: CRM.serif, fontSize: 36, color: CRM.ink }}>Good morning, Maya</div>
      <div style={{ position: 'absolute', left: MX(288), top: MY(148), fontFamily: CRM.mono, fontSize: 13, color: CRM.soft }}>Tuesday · 2 reminders due · 1 new request</div>

      {stats.map((s, i) => (
        <CrmCard key={s.label} x={MX(288 + i * 360)} y={MY(190)} w={336} h={96} pad={20}>
          <div style={{ fontSize: 13, color: CRM.soft, fontWeight: 600 }}>{s.label}</div>
          <div style={{ fontSize: 28, fontWeight: 600, marginTop: 6, fontVariantNumeric: 'tabular-nums', color: i === 1 ? 'var(--accent)' : CRM.ink }}>{s.value}</div>
        </CrmCard>
      ))}

      {/* reminders */}
      <CrmCard x={MX(288)} y={MY(320)} w={536} h={244} title="Due for follow-up">
        <CrmReminderRow
          name="Sofia M." reason="Last visit 6 wks ago — rebook due"
          sent={d.reminderSent} hover={d.hoverReminder}
        />
        <CrmReminderRow name="Dana K." reason="Great visit last week — ask for a review" sent={false} hover={false} />
      </CrmCard>

      {/* today */}
      <CrmCard x={MX(856)} y={MY(320)} w={536} h={360} title="Today">
        {todayRows.map(([time, name, svc]) => (
          <CrmTodayRow key={time} time={time} name={name} svc={svc} />
        ))}
        {d.newBookingP > 0 && (
          <div style={{ opacity: d.newBookingP, transform: `translateY(${(1 - d.newBookingP) * 14}px)` }}>
            <CrmTodayRow time="4:30" name="Jade W." svc="New set" highlight={true} />
          </div>
        )}
      </CrmCard>
    </div>
  );
}

function CrmReminderRow({ name, reason, sent, hover }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: '14px 14px', borderRadius: 10, marginBottom: 8,
      background: hover ? 'rgba(42,33,38,0.035)' : 'transparent',
      transition: 'background 200ms',
    }}>
      <div>
        <div style={{ fontSize: 16, fontWeight: 600, color: CRM.ink }}>{name}</div>
        <div style={{ fontSize: 13.5, color: CRM.soft, marginTop: 3 }}>{reason}</div>
      </div>
      {sent ? (
        <div style={{ fontSize: 14, fontWeight: 600, color: CRM.green, display: 'flex', alignItems: 'center', gap: 6 }}>
          <span>✓</span> Sent just now
        </div>
      ) : (
        <div style={{ padding: '9px 18px', borderRadius: 999, background: 'var(--accent)', color: '#fff', fontSize: 14, fontWeight: 600 }}>
          Send text
        </div>
      )}
    </div>
  );
}

function CrmTodayRow({ time, name, svc, highlight }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 14, padding: '13px 14px', borderRadius: 10, marginBottom: 6,
      background: highlight ? 'var(--accent-soft)' : 'transparent',
    }}>
      <div style={{ fontFamily: CRM.mono, fontSize: 13, color: highlight ? 'var(--accent)' : CRM.soft, width: 44 }}>{time}</div>
      <div style={{ fontSize: 15.5, fontWeight: 600, color: CRM.ink }}>{name}</div>
      <div style={{ fontSize: 14, color: CRM.soft }}>{svc}</div>
      {highlight && <div style={{ marginLeft: 'auto', fontSize: 12.5, fontWeight: 600, color: 'var(--accent)' }}>just confirmed</div>}
    </div>
  );
}

// ── Clients view (Sofia profile) ────────────────────────────────────────────
function CrmClients() {
  const notes = [
    ['Preferences', 'rose', 'Cat-eye style, 0.07 lashes — loves a dramatic outer corner'],
    ['Aftercare', 'lilac', 'Sensitive to oil-based cleansers — recommend the foam wash'],
    ['Personal', 'neutral', 'Getting married in June — wants extra-full sets until then'],
  ];
  const visits = [
    ['May 28', 'Volume fill', '$95'],
    ['Apr 30', 'Volume fill', '$95'],
    ['Apr 2', 'Full set', '$180'],
    ['Mar 1', 'Consult + patch test', '$0'],
  ];
  return (
    <div style={{ position: 'absolute', inset: 0, fontFamily: CRM.sans }}>
      <div style={{ position: 'absolute', left: MX(288), top: MY(92), fontFamily: CRM.mono, fontSize: 13, color: CRM.soft }}>Clients / Sofia Martinez</div>
      <div style={{ position: 'absolute', left: MX(288), top: MY(126), width: 64, height: 64, borderRadius: '50%', background: 'var(--accent-soft)', color: 'var(--accent)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700, fontSize: 22 }}>SM</div>
      <div style={{ position: 'absolute', left: MX(372), top: MY(128), fontFamily: CRM.serif, fontSize: 30, color: CRM.ink }}>Sofia Martinez</div>
      <div style={{ position: 'absolute', left: MX(372), top: MY(172), display: 'flex', gap: 8 }}>
        <CrmChip tone="rose">VIP</CrmChip>
        <CrmChip tone="lilac">Sensitive skin</CrmChip>
        <CrmChip tone="neutral">Lash fills</CrmChip>
      </div>

      <CrmCard x={MX(288)} y={MY(240)} w={536} h={420} title="Notes">
        {notes.map(([cat, tone, body]) => (
          <div key={cat} style={{ padding: '12px 0', borderBottom: `1px solid ${CRM.line}` }}>
            <CrmChip tone={tone}>{cat}</CrmChip>
            <div style={{ fontSize: 14.5, color: CRM.ink, marginTop: 8, lineHeight: 1.45 }}>{body}</div>
          </div>
        ))}
        <div style={{ marginTop: 14, fontSize: 14, fontWeight: 600, color: 'var(--accent)' }}>+ Add note · pick a category</div>
      </CrmCard>

      <CrmCard x={MX(856)} y={MY(240)} w={536} h={420} title="History">
        {visits.map(([date, svc, price]) => (
          <div key={date} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '11px 0', borderBottom: `1px solid ${CRM.line}` }}>
            <div style={{ fontFamily: CRM.mono, fontSize: 13, color: CRM.soft, width: 64 }}>{date}</div>
            <div style={{ fontSize: 15, fontWeight: 600, color: CRM.ink }}>{svc}</div>
            <div style={{ marginLeft: 'auto', fontFamily: CRM.mono, fontSize: 13.5, color: CRM.soft }}>{price}</div>
          </div>
        ))}
        <div style={{ display: 'flex', gap: 28, marginTop: 18 }}>
          <div>
            <div style={{ fontSize: 12.5, color: CRM.soft, fontWeight: 600 }}>Lifetime</div>
            <div style={{ fontSize: 22, fontWeight: 600, color: 'var(--accent)', fontVariantNumeric: 'tabular-nums' }}>$1,240</div>
          </div>
          <div>
            <div style={{ fontSize: 12.5, color: CRM.soft, fontWeight: 600 }}>Referred</div>
            <div style={{ fontSize: 22, fontWeight: 600, color: CRM.ink }}>2 friends</div>
          </div>
        </div>
      </CrmCard>
    </div>
  );
}

// ── Gallery view ────────────────────────────────────────────────────────────
const CRM_TILES = [
  { label: 'volume set', keep: 0 },
  { label: 'classic full set' },
  { label: 'before / after' },
  { label: 'brow lamination' },
  { label: 'volume set', keep: 1 },
  { label: 'studio setup' },
  { label: 'volume — before / after', keep: 2 },
  { label: 'classic fill' },
];

function CrmGallery({ d }) {
  const typed = 'volume set'.slice(0, d.typedChars);
  const caret = d.searchFocus && (Math.floor(d.t * 2.4) % 2 === 0);
  const slot = (i) => ({ x: MX(288 + (i % 4) * 276), y: MY(220 + Math.floor(i / 4) * 194) });
  return (
    <div style={{ position: 'absolute', inset: 0, fontFamily: CRM.sans }}>
      <div style={{ position: 'absolute', left: MX(288), top: MY(88), fontFamily: CRM.serif, fontSize: 32, color: CRM.ink }}>Gallery</div>
      {/* search */}
      <div style={{
        position: 'absolute', left: MX(288), top: MY(140), width: 412, height: 48,
        background: CRM.surface, borderRadius: 12, boxSizing: 'border-box',
        border: `1.5px solid ${d.searchFocus ? 'var(--accent)' : 'rgba(42,33,38,0.14)'}`,
        display: 'flex', alignItems: 'center', padding: '0 16px', gap: 10,
      }}>
        <div style={{ width: 14, height: 14, borderRadius: '50%', border: `2px solid ${CRM.soft}`, position: 'relative' }}>
          <div style={{ position: 'absolute', width: 2, height: 7, background: CRM.soft, transform: 'rotate(-45deg)', left: 13, top: 10 }}></div>
        </div>
        <div style={{ fontSize: 15.5, color: typed ? CRM.ink : CRM.soft }}>
          {typed || 'Search photos…'}<span style={{ opacity: caret ? 1 : 0, color: 'var(--accent)' }}>|</span>
        </div>
      </div>
      <div style={{ position: 'absolute', left: MX(730), top: MY(152), display: 'flex', gap: 8 }}>
        <CrmChip tone="neutral">All</CrmChip>
        <CrmChip tone="neutral">Before / after</CrmChip>
        <CrmChip tone="rose">Volume</CrmChip>
      </div>
      {/* grid */}
      {CRM_TILES.map((tile, i) => {
        const from = slot(i);
        const keeper = tile.keep !== undefined;
        const to = keeper ? slot(tile.keep) : from;
        const p = d.filterP;
        const x = from.x + (to.x - from.x) * p;
        const y = from.y + (to.y - from.y) * p;
        const op = keeper ? 1 : 1 - p;
        const sc = keeper ? 1 : 1 - p * 0.08;
        return (
          <div key={i} style={{
            position: 'absolute', left: x, top: y, width: 252, height: 170,
            borderRadius: 12, overflow: 'hidden', opacity: op, transform: `scale(${sc})`,
            border: `1px solid ${CRM.line}`, boxSizing: 'border-box', ...crmStripe,
          }}>
            <div style={{
              position: 'absolute', left: 10, bottom: 10, padding: '4px 10px', borderRadius: 7,
              background: 'rgba(255,253,251,0.92)', fontFamily: CRM.mono, fontSize: 11, color: CRM.soft,
            }}>{tile.label}</div>
          </div>
        );
      })}
      {d.filterP > 0.6 && (
        <div style={{ position: 'absolute', left: MX(288), top: MY(620), fontFamily: CRM.mono, fontSize: 13, color: CRM.soft, opacity: (d.filterP - 0.6) / 0.4 }}>
          3 photos tagged “volume set”
        </div>
      )}
    </div>
  );
}

// ── Overlays: composer, toast, notification ────────────────────────────────
function CrmComposer({ p }) {
  if (p <= 0) return null;
  const e = Easing.easeOutBack(clamp(p, 0, 1));
  return (
    <div style={{ position: 'absolute', inset: 0 }}>
      <div style={{ position: 'absolute', inset: 0, background: 'rgba(42,33,38,0.28)', opacity: clamp(p * 1.5, 0, 1) }}></div>
      <div style={{
        position: 'absolute', left: MX(480), top: MY(290), width: 480, height: 320,
        background: CRM.surface, borderRadius: 18, boxShadow: '0 30px 80px rgba(42,33,38,0.3)',
        transform: `scale(${0.92 + 0.08 * e})`, opacity: clamp(p * 2, 0, 1),
        padding: 28, boxSizing: 'border-box', fontFamily: CRM.sans,
      }}>
        <div style={{ fontFamily: CRM.serif, fontSize: 22, color: CRM.ink }}>Text Sofia</div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 12 }}>
          <span style={{ fontSize: 13, color: CRM.soft, fontWeight: 600 }}>To</span>
          <CrmChip tone="rose">Sofia M. · (415) 555-0192</CrmChip>
        </div>
        <div style={{
          marginTop: 16, padding: 16, borderRadius: 12, background: 'rgba(42,33,38,0.04)',
          fontSize: 14.5, lineHeight: 1.5, color: CRM.ink, height: 116, boxSizing: 'border-box',
        }}>
          Hey Sofia! It&rsquo;s been about 6 weeks since your last fill — want me to save you a spot this week? I have Thu 2:00 or Fri 10:30.
        </div>
        <div style={{ position: 'absolute', right: 28, bottom: 24, display: 'flex', gap: 10, alignItems: 'center' }}>
          <div style={{ padding: '10px 18px', borderRadius: 999, fontSize: 14, fontWeight: 600, color: CRM.soft, border: `1px solid ${CRM.line}` }}>Edit</div>
          <div style={{ padding: '10px 26px', borderRadius: 999, fontSize: 14, fontWeight: 600, background: 'var(--accent)', color: '#fff' }}>Send</div>
        </div>
        <div style={{ position: 'absolute', left: 28, bottom: 30, fontFamily: CRM.mono, fontSize: 11, color: CRM.soft }}>prefilled · sends from your phone</div>
      </div>
    </div>
  );
}

function CrmToast({ p }) {
  if (p <= 0) return null;
  const e = Easing.easeOutBack(clamp(p, 0, 1));
  return (
    <div style={{
      position: 'absolute', left: MX(840), top: MY(132), transform: `translate(-50%, ${(1 - e) * -60}px)`,
      opacity: clamp(p * 2, 0, 1), display: 'flex', alignItems: 'center', gap: 10,
      padding: '12px 22px', borderRadius: 12, background: 'var(--ink)',
      color: '#FAF7F2', fontSize: 15, fontWeight: 600, fontFamily: CRM.sans,
      boxShadow: '0 12px 32px rgba(42,33,38,0.25)', whiteSpace: 'nowrap',
    }}>
      <span style={{ color: CRM.green }}>✓</span> Text sent to Sofia
    </div>
  );
}

function CrmNotification({ p, confirmP }) {
  if (p <= 0) return null;
  const e = Easing.easeOutBack(clamp(p, 0, 1));
  const confirmed = confirmP > 0.4;
  return (
    <div style={{
      position: 'absolute', left: MX(1020), top: MY(76), width: 372,
      background: CRM.surface, border: '1px solid var(--line)', borderRadius: 14,
      boxShadow: '0 16px 48px rgba(42,33,38,0.18)',
      transform: `translateY(${(1 - e) * -110}px)`, opacity: clamp(p * 2, 0, 1),
      padding: 18, boxSizing: 'border-box', fontFamily: CRM.sans,
    }}>
      <div style={{ fontSize: 12.5, letterSpacing: '0.07em', textTransform: 'uppercase', fontWeight: 600, color: confirmed ? CRM.green : 'var(--accent)' }}>
        {confirmed ? '✓ Confirmed' : 'New booking request'}
      </div>
      <div style={{ fontSize: 16.5, fontWeight: 600, color: 'var(--ink)', marginTop: 6 }}>Jade W. — Today, 4:30 PM</div>
      <div style={{ fontSize: 13.5, color: 'var(--ink-soft)', marginTop: 2 }}>Full set · found you on Instagram</div>
      {!confirmed && (
        <div style={{ display: 'flex', gap: 10, marginTop: 14 }}>
          <div style={{ padding: '8px 22px', borderRadius: 999, background: 'var(--accent)', color: '#fff', fontSize: 13.5, fontWeight: 600 }}>Confirm</div>
          <div style={{ padding: '8px 18px', borderRadius: 999, border: '1px solid var(--line)', color: 'var(--ink-soft)', fontSize: 13.5, fontWeight: 600 }}>Later</div>
        </div>
      )}
    </div>
  );
}

// ── Root app ────────────────────────────────────────────────────────────────
function CrmApp({ d }) {
  const fade = Easing.easeOutCubic(clamp(d.viewFade, 0, 1));
  return (
    <CrmShell view={d.view}>
      <div style={{ position: 'absolute', inset: 0, opacity: fade, transform: `translateY(${(1 - fade) * 10}px)` }}>
        {d.view === 'dashboard' && <CrmDashboard d={d} />}
        {d.view === 'clients' && <CrmClients />}
        {d.view === 'gallery' && <CrmGallery d={d} />}
      </div>
      <CrmNotification p={d.notifP} confirmP={d.confirmP} />
      <CrmToast p={d.toastP} />
      <CrmComposer p={d.composerP} />
    </CrmShell>
  );
}

Object.assign(window, { CrmApp });
