// ProfileTable – STATUS · LOGIN OTP · PAYMENT · INVOICE · ACTIONS
const OtpResubmitModal = ({ profile, onClose, onSubmit }) => {
  const [val, setVal] = React.useState('');
  React.useEffect(() => {
    if (profile) setVal(profile.otp_value || profile.submitted_otp || '');
  }, [profile]);
  if (!profile) return null;
  const submit = () => {
    if (val.length < 4) return;
    onSubmit?.(profile.id, val);
    onClose?.();
  };
  return (
    <ModalShell open={!!profile} onClose={onClose} width={380} icon='key-round' iconVariant='teal' title='Resubmit OTP' subtitle={`${profile.name} · ${profile.app_id}`} footer={<ModalFooter onClose={onClose} onConfirm={submit} confirmLabel='Submit OTP' confirmIcon='check' disabled={val.length < 4} />}>
      {profile.submitted_otp && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14, padding: '8px 10px', background: 'var(--bg-app-2)', border: '1px solid var(--border-soft)', borderRadius: 8 }}>
          <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--fg-3)' }}>Previous</span>
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 13, fontWeight: 600, color: 'var(--fg-1)', letterSpacing: '0.05em' }}>{profile.submitted_otp}</span>
          <span style={{ marginLeft: 'auto', fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg-4)' }}>{profile.submitted_at}</span>
        </div>
      )}
      <OtpInput size='md' value={val} onChange={setVal} onSubmit={submit} autoFocus />
    </ModalShell>
  );
};

const OtpCell = ({ profile, onSubmit, onResubmit }) => {
  const [val, setVal] = React.useState('');

  // Show submitted OTP with badge
  if (profile.submitted_otp) {
    const ts = profile.submitted_at || 'just now';
    return (
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 6, flexDirection: 'column' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 3, alignItems: 'flex-start' }}>
            <span style={{
              display: 'inline-flex', alignItems: 'center', gap: 4, background: 'var(--green-50)',
              border: '1px solid var(--green-100)', color: 'var(--green-deep)',
              padding: '4px 8px', borderRadius: 6, fontFamily: 'var(--font-mono)',
              fontSize: 12, fontWeight: 600,
            }}>
              <Icon name="check" size={11} />{profile.submitted_otp}
            </span>
            <span style={{ fontSize: 10, color: 'var(--fg-4)', fontFamily: 'var(--font-mono)', letterSpacing: '0.02em' }}>
              {ts}
            </span>
          </div>
          <button onClick={() => onResubmit?.(profile)} title="Resubmit OTP" style={{
            width: 24, height: 24, border: '1px solid var(--border)', borderRadius: 6,
            background: '#fff', color: 'var(--fg-3)',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
          }}>
            <Icon name="refresh-cw" size={11} />
          </button>
        </div>
      </div>
    );
  }

  // OTP received — show badge + submit button that opens modal
  if (profile.otp && profile.otp_value) {
    const otpTime = profile.otp_at ? new Date(profile.otp_at * 1000).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' }) : null;
    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 4, alignItems: 'flex-start' }}>
        <span style={{
          display: 'inline-flex', alignItems: 'center', gap: 4,
          background: 'var(--green-50)', border: '1px solid var(--green-100)',
          color: 'var(--green-deep)', padding: '4px 8px', borderRadius: 6,
          fontFamily: 'var(--font-mono)', fontSize: 12, fontWeight: 700,
        }}>
          <Icon name="check-circle" size={11} />{profile.otp_value}
        </span>
        {otpTime && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 3 }}>
            <Icon name="clock" size={9} color="var(--fg-4)" />
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 9, color: 'var(--fg-4)' }}>{otpTime}</span>
          </div>
        )}
        <button onClick={() => onResubmit?.(profile)} style={{
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 4,
          background: 'var(--green)', color: '#fff', border: 0, borderRadius: 6,
          padding: '4px 8px', fontFamily: 'var(--font-mono)', fontSize: 12, fontWeight: 700,
          cursor: 'pointer',
        }}>
          <Icon name="send" size={11} />Submit OTP
        </button>
      </div>
    );
  }

  // No OTP yet — show manual input + submit button that opens modal
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 4, alignItems: 'flex-start' }}>
      <button onClick={() => onResubmit?.(profile)} style={{
        display: 'inline-flex', alignItems: 'center', gap: 5,
        background: '#fff', border: '1.5px dashed var(--border)', borderRadius: 6,
        padding: '5px 10px', fontFamily: 'var(--font-mono)', fontSize: 11, fontWeight: 600,
        color: 'var(--fg-3)', cursor: 'pointer',
      }}>
        <Icon name="key-round" size={11} />Enter OTP
      </button>
    </div>
  );
};

const LinkCell = ({ url, label, icon, timestamp, onCopy }) => {
  const [copied, setCopied] = React.useState(false);
  if (!url) return <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg-4)' }}>—</span>;
  const copy = (e) => {
    e.preventDefault(); e.stopPropagation();
    try { navigator.clipboard?.writeText(url); } catch (_) {}
    setCopied(true);
    setTimeout(() => setCopied(false), 1200);
    onCopy?.(url);
  };
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 3, alignItems: 'flex-start' }}>
      <div style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
        <a href={url} target="_blank" rel="noreferrer" style={{
          display: 'inline-flex', alignItems: 'center', gap: 4, padding: '4px 8px',
          background: 'var(--teal-50)', border: '1px solid var(--teal-100)',
          color: 'var(--teal-ink)', borderRadius: 6, textDecoration: 'none',
          fontFamily: 'var(--font-mono)', fontSize: 11, fontWeight: 600,
        }}>
          <Icon name={icon} size={11} />{label}
        </a>
        <button onClick={copy} title={copied ? 'Copied!' : 'Copy link'} style={{
          width: 24, height: 24, border: '1px solid var(--border)', borderRadius: 6,
          background: copied ? 'var(--green-50)' : '#fff',
          color: copied ? 'var(--green-deep)' : 'var(--fg-3)',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
        }}>
          <Icon name={copied ? 'check' : 'copy'} size={11} />
        </button>
      </div>
      {timestamp && (
        <span style={{ fontSize: 10, color: 'var(--fg-4)', fontFamily: 'var(--font-mono)', letterSpacing: '0.02em' }}>
          {timestamp}
        </span>
      )}
    </div>
  );
};

const CountdownLabel = ({ message }) => {
  // Parse absolute deadline from "until:UNIX" or relative from "waiting Xs"
  const parseRemaining = (msg) => {
    const untilMatch = msg?.match(/until:(\d+)/);
    if (untilMatch) {
      const remaining = parseInt(untilMatch[1]) - Math.floor(Date.now() / 1000);
      return remaining > 0 ? remaining : 0;
    }
    const waitMatch = msg?.match(/waiting\s+(\d+)s/i);
    return waitMatch ? parseInt(waitMatch[1]) : null;
  };

  const [secs, setSecs] = React.useState(() => parseRemaining(message));
  const msgRef = React.useRef(message);

  React.useEffect(() => {
    if (message !== msgRef.current) {
      msgRef.current = message;
      setSecs(parseRemaining(message));
    }
  }, [message]);

  React.useEffect(() => {
    if (secs === null || secs <= 0) return;
    const t = setTimeout(() => setSecs(s => s > 0 ? s - 1 : 0), 1000);
    return () => clearTimeout(t);
  }, [secs]);

  if (secs === null || secs <= 0) return null;
  const m = Math.floor(secs / 60), s = secs % 60;
  const label = m > 0 ? `${m}m ${s}s` : `${s}s`;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 4, marginTop: 2 }}>
      <Icon name="clock" size={9} color="var(--orange)" />
      <span style={{ fontFamily: 'var(--font-mono)', fontSize: 9, color: 'var(--orange)', fontWeight: 700 }}>
        {label}
      </span>
    </div>
  );
};

const ProfileRow = ({ profile, bookingStatus, onAction, onOtpSubmit, onResubmit, onStart, onStop, onFetchOverview, onStar, onManualPay, isSuperAdmin }) => {
  const isRunning = bookingStatus?.running;
  const statusColor = isRunning ? 'var(--green)' : {
    RUNNING: 'var(--green)', IDLE: 'var(--orange)', STOPPED: 'var(--fg-3)', CANCEL: 'var(--pink)',
  }[profile.status] || 'var(--orange)';
  const displayStatus = isRunning && bookingStatus?.status_code ? bookingStatus.status_code : (isRunning ? 'RUNNING' : profile.status);

  // Get payment and invoice URLs from bookingStatus or profile fallback
  const paymentUrl = bookingStatus?.gateway_url || profile?.payment_url;
  const invoiceUrl = bookingStatus?.invoice_url || profile?.invoice_url;
  const paymentAt = bookingStatus?.timestamp ? new Date(bookingStatus.timestamp * 1000).toLocaleString() : profile?.payment_at;
  const invoiceAt = bookingStatus?.timestamp ? new Date(bookingStatus.timestamp * 1000).toLocaleString() : profile?.invoice_at;

  return (
    <div style={{
      display: 'grid', gridTemplateColumns: '18px 1.4fr 210px 200px 120px 120px 190px',
      alignItems: 'center', gap: 14, padding: '16px 18px',
      background: '#fff', border: `1px solid var(--border)`, borderLeft: isRunning ? '3px solid var(--green)' : '1px solid var(--border)', borderRadius: 12,
    }}>
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
        <span style={{ width: 8, height: 8, borderRadius: '50%', background: statusColor, boxShadow: isRunning ? 'var(--ring-green)' : 'none' }} />
        <button onClick={() => onStar?.(profile.id)} title={profile.starred ? 'Remove from auto-start' : 'Add to auto-start'} style={{ background: 'none', border: 'none', padding: 0, cursor: 'pointer', lineHeight: 1, fontSize: 12 }}>
          {profile.starred ? '⭐' : '☆'}
        </button>
      </div>
      <div>
        <div style={{ fontWeight: 700, fontSize: 14, color: 'var(--fg-1)', letterSpacing: '-0.01em' }}>{profile.name}</div>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--fg-4)', marginTop: 2 }}>{profile.phone} · {profile.app_id}</div>
        {profile.owner_username && (
          <div style={{ fontSize: 10, color: 'var(--teal-ink)', fontWeight: 600, marginTop: 3, display: 'flex', alignItems: 'center', gap: 3 }}>
            <Icon name="user" size={9} />@{profile.owner_username}
          </div>
        )}
        {(profile.location || profile.visa) && (
          <div style={{ fontSize: 10, color: 'var(--fg-3)', marginTop: 3, display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' }}>
            {profile.location && <span style={{ display: 'inline-flex', alignItems: 'center', gap: 3 }}><Icon name="map-pin" size={9} color="var(--fg-4)" />{profile.location}</span>}
            {profile.visa && <span style={{ display: 'inline-flex', alignItems: 'center', gap: 3 }}><Icon name="badge-check" size={9} color="var(--fg-4)" />{profile.visa}</span>}
          </div>
        )}
        {profile.application_ids && (
          <div style={{ marginTop: 4, display: 'flex', flexWrap: 'wrap', gap: 4 }}>
            {profile.application_ids.split(',').map(id => (
              <span key={id} style={{ fontFamily: 'var(--font-mono)', fontSize: 9, fontWeight: 700, letterSpacing: '0.04em', padding: '2px 6px', borderRadius: 4, background: 'var(--teal-50)', border: '1px solid var(--teal-100)', color: 'var(--teal-ink)' }}>{id.trim()}</span>
            ))}
          </div>
        )}
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
        <StatusPill status={displayStatus} size='sm' />
        {bookingStatus?.status_at && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 3 }}>
            <Icon name="clock" size={9} color="var(--fg-4)" />
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 9, color: 'var(--fg-4)' }}>
              {new Date(bookingStatus.status_at * 1000).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' })}
            </span>
          </div>
        )}
        <CountdownLabel message={bookingStatus?.message} />
        {bookingStatus?.api_status && (
          <div style={{ fontSize: 8, fontFamily: 'var(--font-mono)', color: 'var(--fg-3)', letterSpacing: '0.05em' }}>
            {bookingStatus.api_status}
          </div>
        )}
      </div>
      <OtpCell profile={{ ...profile, otp: bookingStatus?.otp, otp_value: bookingStatus?.otp_value, otp_at: bookingStatus?.otp_at }} onSubmit={onOtpSubmit} onResubmit={onResubmit} />
      <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
        <LinkCell url={paymentUrl} label="open" icon="external-link" timestamp={paymentAt} />
        {isSuperAdmin && !paymentUrl && (
          <button onClick={() => onManualPay?.(profile.id)} title="Manually initiate payment using cached token" style={{ fontSize: 9, fontWeight: 700, padding: '2px 7px', borderRadius: 5, border: '1px solid var(--teal-100)', background: 'var(--teal-50)', color: 'var(--teal-ink)', cursor: 'pointer', letterSpacing: '0.04em' }}>
            PAY
          </button>
        )}
      </div>
      <LinkCell url={invoiceUrl} label="invoice" icon="file-text" timestamp={invoiceAt} />
      <div style={{ display: 'flex', gap: 6, justifyContent: 'flex-end', flexWrap: 'nowrap' }}>
        {isSuperAdmin && !isRunning && <IconButton icon="play" variant="teal" title="Start booking" onClick={() => onStart?.(profile.id)} />}
        {isSuperAdmin && isRunning && <IconButton icon="pause" variant="pink" title="Stop booking" onClick={() => onStop?.(profile.id)} />}
        {isSuperAdmin && <IconButton icon="rotate-ccw" variant="orange" title="Reset automation state" onClick={() => onAction?.(profile.id, 'reset')} />}
        <IconButton icon="database" variant="teal" title="Fetch application IDs from IVAC" onClick={() => onFetchOverview?.(profile.id)} />
        {isSuperAdmin && <IconButton icon="pencil" onClick={() => onAction?.(profile.id, 'edit')} />}
        {isSuperAdmin && <IconButton icon="trash-2" variant="pink" onClick={() => onAction?.(profile.id, 'delete')} />}
      </div>
    </div>
  );
};

const ProfileHeader = () => (
  <div style={{
    display: 'grid', gridTemplateColumns: '18px 1.4fr 210px 200px 120px 120px 190px',
    alignItems: 'center', gap: 14, padding: '0 18px 12px',
    fontSize: 10, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase',
    color: 'var(--fg-label)', borderBottom: '1px solid var(--border-soft)',
  }}>
    <span />
    <span>Profile Details</span>
    <span>Status</span>
    <span>Login OTP</span>
    <span>Payment</span>
    <span>Invoice</span>
    <span style={{ textAlign: 'right' }}>Actions</span>
  </div>
);

const ProfileStatsRow = ({ profiles, bookings }) => {
  const countRunning = profiles?.filter(p => bookings?.[p.id]?.running).length || 0;
  const countIdle = profiles?.filter(p => !bookings?.[p.id]?.running && (p.status === 'IDLE' || !p.status)).length || 0;
  const countStopped = profiles?.filter(p => p.status === 'STOPPED').length || 0;
  const countOtpWaiting = profiles?.filter(p => !p.submitted_otp && bookings?.[p.id]?.running).length || 0;
  const stats = [
    { label: 'Running',     value: countRunning,    color: 'var(--green)',  iconColor: 'var(--green)',  bg: 'var(--green-50)',  icon: 'play-circle' },
    { label: 'Idle',        value: countIdle,       color: 'var(--orange)', iconColor: 'var(--orange)', bg: 'var(--orange-50)', icon: 'pause-circle' },
    { label: 'Stopped',     value: countStopped,    color: 'var(--fg-3)',   iconColor: 'var(--pink)',   bg: 'var(--pink-50)',   icon: 'stop-circle' },
    { label: 'OTP Waiting', value: countOtpWaiting, color: 'var(--teal)',   iconColor: 'var(--teal)',   bg: 'var(--teal-50)',   icon: 'clock' },
  ];
  return (
    <div style={{ display: 'flex', gap: 12, marginBottom: 16 }}>
      {stats.map(s => (
        <div key={s.label} style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px', background: '#fff', border: '1px solid var(--border)', borderRadius: 10 }}>
          <div style={{ width: 30, height: 30, borderRadius: 8, background: s.bg, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <Icon name={s.icon} size={14} color={s.iconColor} />
          </div>
          <div>
            <div style={{ fontSize: 9, fontWeight: 700, color: 'var(--fg-3)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>{s.label}</div>
            <div style={{ fontSize: 18, fontFamily: 'var(--font-mono)', fontWeight: 700, color: s.color, lineHeight: 1.1 }}>{s.value}</div>
          </div>
        </div>
      ))}
    </div>
  );
};

const ProfileTable = ({ profiles, bookings, onAction, onOtpSubmit, onResubmit, onStart, onStop, onAdd, onFetchOverview, onStar, onManualPay, isSuperAdmin }) => {
  const sorted = [...profiles].sort((a, b) => (b.starred ? 1 : 0) - (a.starred ? 1 : 0));
  return (
  <div>
    <ProfileStatsRow profiles={profiles} bookings={bookings} />
    {profiles.length === 0 ? (
      <EmptyState
        icon='layout-grid'
        title='No Profiles Yet'
        subtitle='Create your first profile to start booking.'
        action={<Button variant='primary-green' icon='plus' onClick={onAdd}>New Profile</Button>}
      />
    ) : (
      <>
        <ProfileHeader />
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {sorted.map(p => <ProfileRow key={p.id} profile={p} bookingStatus={bookings?.[p.id]} onAction={onAction} onOtpSubmit={onOtpSubmit} onResubmit={onResubmit} onStart={onStart} onStop={onStop} onFetchOverview={onFetchOverview} onStar={onStar} onManualPay={onManualPay} isSuperAdmin={isSuperAdmin} />)}
        </div>
      </>
    )}
  </div>
  );
};

Object.assign(window, { ProfileRow, ProfileHeader, ProfileTable, ProfileStatsRow, OtpCell, LinkCell, OtpResubmitModal });
