import React, { useState } from 'react'
import ReactDOM from 'react-dom/client'

/* ReputationOS — self-serve client portal for local businesses.
   This is the "delivery" from Greg Isenberg's playbook: the customer logs in,
   sees every review + response status + rating trend without asking anyone.
   Demo data = one HK dental clinic. Real agent wires live review feeds. */

const REVIEWS = [
  { id: 1, src: 'Google', name: 'M. Chan', rating: 5, time: '2h ago', text: 'Dr. Lee fixed my toothache same day. Reception was fast and the price was fair.', status: 'needs_reply', reply: null },
  { id: 2, src: 'Google', name: 'A. Wong', rating: 4, time: '1d ago', text: 'Good experience overall. Waited 20 min past appointment but the care was excellent.', status: 'needs_reply', reply: null },
  { id: 3, src: 'OpenRice', name: 'J. Lam', rating: 5, time: '3d ago', text: 'Best dentist in Central. Booking online was easy.', status: 'replied', reply: 'Thank you J! We appreciate you trusting us with your smile.' },
  { id: 4, src: 'Google', name: 'S. Ho', rating: 2, time: '5d ago', text: 'Receptionist was rude on the phone. Dental work was fine but the attitude put me off.', status: 'flagged', reply: null },
  { id: 5, src: 'Google', name: 'K. Ng', rating: 5, time: '1w ago', text: 'Took my son here for a checkup, they were patient and gentle. Will come back.', status: 'replied', reply: 'So glad your son felt comfortable, K! See you at the next checkup.' },
]

const STATS = [
  { label: 'Avg rating', value: '4.6', delta: '+0.2', up: true },
  { label: 'New reviews (30d)', value: '23', delta: '+8', up: true },
  { label: 'Response rate', value: '87%', delta: '+12%', up: true },
  { label: 'Reviews needing reply', value: '2', delta: '↓', up: false },
]

function App() {
  const [tab, setTab] = useState('reviews')
  const [replies, setReplies] = useState({})
  const [draftFor, setDraftFor] = useState(null)
  const [draft, setDraft] = useState('')

  function sendReply(id) {
    setReplies({ ...replies, [id]: draft })
    setDraftFor(null); setDraft('')
  }

  return (
    <div style={s.wrap}>
      <div style={s.sidebar}>
        <div style={s.logo}><span style={s.logoMark}>R</span> ReputationOS</div>
        <div style={s.clientName}>Dr. Lee Dental · Central</div>
        <nav style={s.nav}>
          <NavBtn active={tab === 'reviews'} onClick={() => setTab('reviews')} icon="⭐" label="Reviews" />
          <NavBtn active={tab === 'analytics'} onClick={() => setTab('analytics')} icon="📈" label="Analytics" />
          <NavBtn active={tab === 'settings'} onClick={() => setTab('settings')} icon="⚙️" label="Settings" />
        </nav>
        <div style={s.sideFoot}>Powered by Genesis Agent · checked 4 min ago</div>
      </div>

      <div style={s.main}>
        {tab === 'reviews' && <ReviewsTab reviews={REVIEWS} replies={replies} draftFor={draftFor} draft={draft} setDraftFor={setDraftFor} setDraft={setDraft} sendReply={sendReply} />}
        {tab === 'analytics' && <AnalyticsTab />}
        {tab === 'settings' && <SettingsTab />}
      </div>
    </div>
  )
}

function NavBtn({ active, onClick, icon, label }) {
  return (
    <button onClick={onClick} style={{ ...s.navBtn, background: active ? 'rgba(255,255,255,0.08)' : 'transparent', color: active ? '#fff' : '#94a3b8' }}>
      <span>{icon}</span> {label}
    </button>
  )
}

function ReviewsTab({ reviews, replies, draftFor, draft, setDraftFor, setDraft, sendReply }) {
  const needsReply = reviews.filter(r => r.status === 'needs_reply').length
  const flagged = reviews.filter(r => r.status === 'flagged').length
  return (
    <div>
      <div style={s.head}><h1 style={s.h1}>Reviews</h1><div style={s.headChips}><Chip label={`${needsReply} need reply`} color="#f59e0b" /><Chip label={`${flagged} flagged`} color="#ef4444" /></div></div>
      <div style={s.statsRow}>{STATS.map(st => <StatCard key={st.label} {...st} />)}</div>
      <div style={s.reviewList}>
        {reviews.map(r => {
          const replied = replies[r.id] || r.reply
          return (
            <div key={r.id} style={s.reviewCard}>
              <div style={s.reviewTop}>
                <div>
                  <span style={s.reviewSrc}>{r.src}</span>
                  <span style={s.reviewName}>{r.name}</span>
                </div>
                <span style={s.stars}>{'★'.repeat(r.rating)}{'☆'.repeat(5 - r.rating)}</span>
              </div>
              <p style={s.reviewText}>{r.text}</p>
              <div style={s.reviewMeta}><span>{r.time}</span></div>

              {r.status === 'needs_reply' && !replied && draftFor !== r.id && (
                <button style={s.replyBtn} onClick={() => { setDraftFor(r.id); setDraft(`Thank you ${r.name.split(' ')[0]} for the feedback — we really appreciate it.`) }}>✍️ Draft reply</button>
              )}
              {draftFor === r.id && (
                <div style={s.draftBox}>
                  <textarea style={s.textarea} value={draft} onChange={e => setDraft(e.target.value)} rows={3} />
                  <div style={s.draftActions}>
                    <button style={s.sendBtn} onClick={() => sendReply(r.id)}>Send reply</button>
                    <button style={s.cancelBtn} onClick={() => setDraftFor(null)}>Cancel</button>
                  </div>
                </div>
              )}
              {replied && <div style={s.repliedNote}>✓ Replied: "{replied}"</div>}
              {r.status === 'flagged' && <div style={s.flagNote}>⚠️ Negative — needs human review before reply</div>}
            </div>
          )
        })}
      </div>
    </div>
  )
}

function AnalyticsTab() {
  return (
    <div>
      <div style={s.head}><h1 style={s.h1}>Analytics</h1></div>
      <div style={s.statsRow}>{STATS.map(st => <StatCard key={st.label} {...st} />)}</div>
      <div style={s.chart}>
        <div style={s.chartTitle}>Rating trend — last 6 months</div>
        <RatingChart />
      </div>
      <div style={s.insight}>
        <div style={s.insightTitle}>Agent insight</div>
        <p>Your 4.6 avg is above the Central HK dental average of 4.2. The 2★ review about reception is your top risk — 1 in 4 recent mentions reference front-desk attitude. Recommended: reply personally to that reviewer and log the reception protocol.</p>
      </div>
    </div>
  )
}

function RatingChart() {
  const bars = [4.1, 4.2, 4.3, 4.5, 4.4, 4.6]
  return (
    <div style={s.bars}>
      {bars.map((v, i) => (
        <div key={i} style={s.barCol}>
          <div style={{ ...s.bar, height: `${(v / 5) * 160}px` }} />
          <span style={s.barLabel}>M{i + 1}</span>
        </div>
      ))}
    </div>
  )
}

function SettingsTab() {
  return (
    <div>
      <div style={s.head}><h1 style={s.h1}>Settings</h1></div>
      <div style={s.settingRow}><span>Auto-reply to 4★+ reviews</span><Toggle on={true} /></div>
      <div style={s.settingRow}><span>Flag negative reviews for manual review</span><Toggle on={true} /></div>
      <div style={s.settingRow}><span>Weekly digest email</span><Toggle on={true} /></div>
      <div style={s.settingRow}><span>Monitor competitors</span><Toggle on={false} /></div>
      <p style={s.settingsNote}>These controls drive the agent behind the scenes. Change one, and the agent's behavior updates within minutes.</p>
    </div>
  )
}

function Toggle({ on }) {
  return <div style={{ ...s.toggle, background: on ? '#3b82f6' : '#334155' }}><div style={{ ...s.toggleDot, marginLeft: on ? 20 : 2 }} /></div>
}

function Chip({ label, color }) { return <span style={{ ...s.chip, color, borderColor: color }}>{label}</span> }
function StatCard({ label, value, delta, up }) {
  return (
    <div style={s.statCard}>
      <div style={s.statLabel}>{label}</div>
      <div style={s.statValue}>{value}</div>
      <div style={{ ...s.statDelta, color: up ? '#34d399' : '#f59e0b' }}>{delta}</div>
    </div>
  )
}

const s = {
  wrap: { minHeight: '100vh', display: 'flex', background: '#0f172a', fontFamily: '-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif', color: '#e2e8f0' },
  sidebar: { width: 240, background: '#0b1120', padding: '24px 16px', display: 'flex', flexDirection: 'column', gap: 20, flexShrink: 0 },
  logo: { fontSize: 18, fontWeight: 800, display: 'flex', alignItems: 'center', gap: 8 },
  logoMark: { width: 30, height: 30, borderRadius: 8, background: 'linear-gradient(135deg,#3b82f6,#8b5cf6)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800, color: '#fff' },
  clientName: { fontSize: 12, color: '#64748b', padding: '8px 12px', background: 'rgba(255,255,255,0.04)', borderRadius: 8 },
  nav: { display: 'flex', flexDirection: 'column', gap: 6 },
  navBtn: { display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', borderRadius: 8, border: 'none', cursor: 'pointer', fontSize: 14, fontWeight: 600, textAlign: 'left' },
  sideFoot: { marginTop: 'auto', fontSize: 11, color: '#475569' },
  main: { flex: 1, padding: '28px 32px', maxWidth: 900 },
  head: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 },
  h1: { fontSize: 24, fontWeight: 800, margin: 0 },
  headChips: { display: 'flex', gap: 8 },
  chip: { fontSize: 12, fontWeight: 600, padding: '4px 10px', borderRadius: 20, border: '1px solid' },
  statsRow: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(160px,1fr))', gap: 12, marginBottom: 24 },
  statCard: { background: '#1e293b', borderRadius: 12, padding: 16, border: '1px solid rgba(255,255,255,0.05)' },
  statLabel: { fontSize: 12, color: '#94a3b8' },
  statValue: { fontSize: 24, fontWeight: 800, marginTop: 4 },
  statDelta: { fontSize: 12, fontWeight: 600, marginTop: 2 },
  reviewList: { display: 'flex', flexDirection: 'column', gap: 12 },
  reviewCard: { background: '#1e293b', borderRadius: 14, padding: 18, border: '1px solid rgba(255,255,255,0.05)' },
  reviewTop: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 },
  reviewSrc: { fontSize: 11, fontWeight: 700, color: '#3b82f6', background: 'rgba(59,130,246,0.1)', padding: '2px 8px', borderRadius: 6, marginRight: 8 },
  reviewName: { fontSize: 14, fontWeight: 600, color: '#cbd5e1' },
  stars: { color: '#f59e0b', letterSpacing: 1 },
  reviewText: { fontSize: 14, lineHeight: 1.5, color: '#e2e8f0', margin: '0 0 8px' },
  reviewMeta: { fontSize: 12, color: '#64748b' },
  replyBtn: { marginTop: 10, padding: '8px 14px', borderRadius: 8, border: '1px solid #3b82f6', background: 'transparent', color: '#60a5fa', cursor: 'pointer', fontSize: 13, fontWeight: 600 },
  draftBox: { marginTop: 10, background: '#0f172a', borderRadius: 10, padding: 12 },
  textarea: { width: '100%', background: '#1e293b', border: '1px solid rgba(255,255,255,0.1)', borderRadius: 8, color: '#e2e8f0', padding: 10, fontSize: 14, fontFamily: 'inherit', resize: 'vertical' },
  draftActions: { display: 'flex', gap: 8, marginTop: 8 },
  sendBtn: { padding: '8px 16px', borderRadius: 8, border: 'none', background: '#3b82f6', color: '#fff', cursor: 'pointer', fontWeight: 600 },
  cancelBtn: { padding: '8px 16px', borderRadius: 8, border: '1px solid rgba(255,255,255,0.15)', background: 'transparent', color: '#94a3b8', cursor: 'pointer' },
  repliedNote: { marginTop: 10, fontSize: 13, color: '#34d399' },
  flagNote: { marginTop: 10, fontSize: 13, color: '#f59e0b', fontWeight: 600 },
  chart: { background: '#1e293b', borderRadius: 14, padding: 20, border: '1px solid rgba(255,255,255,0.05)', marginTop: 16 },
  chartTitle: { fontSize: 14, fontWeight: 600, color: '#cbd5e1', marginBottom: 16 },
  bars: { display: 'flex', alignItems: 'flex-end', gap: 12, height: 180 },
  barCol: { display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, flex: 1 },
  bar: { width: '100%', maxWidth: 40, borderRadius: '6px 6px 0 0', background: 'linear-gradient(180deg,#3b82f6,#8b5cf6)' },
  barLabel: { fontSize: 11, color: '#64748b' },
  insight: { background: 'rgba(139,92,246,0.08)', border: '1px solid rgba(139,92,246,0.3)', borderRadius: 14, padding: 18, marginTop: 16 },
  insightTitle: { fontSize: 13, fontWeight: 700, color: '#a78bfa', marginBottom: 6 },
  settingRow: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '16px 0', borderBottom: '1px solid rgba(255,255,255,0.05)' },
  toggle: { width: 42, height: 24, borderRadius: 12, cursor: 'pointer', transition: 'background .2s', display: 'flex', alignItems: 'center' },
  toggleDot: { width: 20, height: 20, borderRadius: 10, background: '#fff', transition: 'margin .2s' },
  settingsNote: { fontSize: 13, color: '#64748b', marginTop: 16, lineHeight: 1.5 },
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />)
