// ===========================================================
// Telesale Console — active call with script + customer context
// ===========================================================

function TelesaleScreen({ onOpenCustomer, onLogOrder }) {
  const [activeIdx, setActiveIdx] = useState(0);
  const [callState, setCallState] = useState('idle'); // idle | calling | active | wrap
  const [duration, setDuration] = useState(0);
  const [muted, setMuted] = useState(false);
  const [note, setNote] = useState('');
  const [outcome, setOutcome] = useState(null);
  const [callbackAt, setCallbackAt] = useState(D.iso(1) + 'T10:00');

  // Tick duration when active
  useEffect(() => {
    if (callState !== 'active') return;
    const t = setInterval(() => setDuration(d => d + 1), 1000);
    return () => clearInterval(t);
  }, [callState]);

  const queueItem = D.callQueue[activeIdx] || D.callQueue[0];
  const customer = D.customers.find(c => c.id === queueItem.customer) || D.customers[0];
  const sessOrders = (window.TVS_SESSION.ordersByCustomer[customer.id] || []);
  const orders = [...sessOrders, ...(D.ordersByCustomer[customer.id] || [])];

  const formatTimer = (s) => {
    const m = Math.floor(s/60); const sec = s%60;
    return `${String(m).padStart(2,'0')}:${String(sec).padStart(2,'0')}`;
  };

  const startCall = () => { setCallState('calling'); setDuration(0); setTimeout(() => setCallState('active'), 1200); };
  const endCall   = () => { setCallState('wrap'); };
  const OUTCOME_LABELS = { success:'Bán thành công', callback:'Đặt lịch lại', nointerest:'Không quan tâm', nopickup:'Không nghe máy', wrong:'Sai số', other:'Khác' };
  const finishWrap = () => {
    // Lưu kết quả cuộc gọi vào hồ sơ khách — như lời hứa "sẽ được cập nhật vào CRM"
    const label = OUTCOME_LABELS[outcome] || outcome;
    window.TVS_SESSION.addNote(customer.id, {
      text: `[Kết quả cuộc gọi: ${label} · ${formatTimer(duration)}]${note ? ' ' + note : ''}`,
      tag: 'contact', who: 'Telesale', role: 'Telesale',
    });
    if (outcome === 'callback' && callbackAt) {
      const [d, t] = callbackAt.split('T');
      window.TVS_SESSION.addFollowUp(customer.id, {
        reason: 'Gọi lại theo hẹn' + (note ? ' — ' + note : ''), date: d, time: t || '10:00',
        channel: 'Gọi điện', who: 'Telesale', role: 'Telesale',
      });
    }
    window.tvsToast(`Đã lưu kết quả: ${label}`);
    setCallState('idle'); setDuration(0); setNote(''); setOutcome(null);
    setActiveIdx(i => Math.min(i+1, D.callQueue.length-1));
  };

  // Scripts
  const scripts = {
    winback: {
      title: 'Script Win-back',
      sections: [
        { h: 'Mở đầu (15s)', body: 'Chào anh/chị {name}, em {agent} từ The Vitamin Shoppe. Em thấy đã lâu chưa gặp anh/chị — không biết sản phẩm {lastProduct} dùng có ổn không ạ?' },
        { h: 'Lắng nghe', body: '• Để khách trả lời tự nhiên\n• Ghi nhận lý do (giá / hiệu quả / quên...)\n• Đồng cảm trước khi đề xuất' },
        { h: 'Đề xuất', body: 'Hiện em có combo giảm 20% cho khách quay lại — combo {category} + tặng kèm hộp sample. Anh/chị có muốn em đặt thử không ạ?' },
        { h: 'Kết thúc', body: 'Cảm ơn anh/chị đã dành thời gian. Em sẽ gửi link qua Zalo trong 5 phút nữa nhé.' },
      ],
    },
    restock: {
      title: 'Script Sản phẩm sắp hết',
      sections: [
        { h: 'Mở đầu', body: 'Chào anh/chị {name}, em từ The Vitamin Shoppe. Theo lịch dùng, sản phẩm {lastProduct} sắp hết — em chủ động gọi để hỗ trợ đặt lại ạ.' },
        { h: 'Xác nhận', body: '• Kiểm tra còn dùng đều không\n• Hỏi vị/dạng quen thuộc\n• Có muốn đổi sang gói lớn hơn để tiết kiệm?' },
        { h: 'Đề xuất', body: 'Đặt lại hôm nay free ship + tích gấp đôi điểm thành viên. Em chốt đơn ngay nhé?' },
      ],
    },
    crosssell: {
      title: 'Script Cross-sell',
      sections: [
        { h: 'Mở đầu', body: 'Chào anh/chị {name}, em chúc anh/chị một ngày tốt lành. Theo lịch sử mua, anh/chị đang dùng Multivitamin — em có gợi ý tốt cho cả nhà...' },
        { h: 'Câu chuyện', body: 'Nhiều khách dùng Multivitamin thường bổ sung thêm Probiotic cho hệ tiêu hóa, đặc biệt với trẻ nhỏ. Anh/chị đã thử chưa?' },
        { h: 'Đề xuất combo', body: 'Combo Family Health: Multi 120v + Probiotic 60v + Kids Gummy → giảm 15% tổng, tặng kèm bình lắc.' },
      ],
    },
    onboard: {
      title: 'Script Onboarding khách mới',
      sections: [
        { h: 'Mở đầu', body: 'Chào mừng anh/chị đến với The Vitamin Shoppe! Em là {agent}, hỗ trợ chăm sóc khách hàng mới.' },
        { h: 'Khám phá nhu cầu', body: '• Đang quan tâm sản phẩm gì?\n• Mục tiêu sức khỏe (giảm cân, tăng cơ, sắc đẹp, giấc ngủ...)\n• Đang dùng sản phẩm tương tự không?' },
        { h: 'Hướng dẫn dùng', body: 'Em gửi anh/chị video hướng dẫn dùng + lịch dùng cá nhân hóa qua Zalo. Có gì khó cứ inbox em.' },
      ],
    },
  };
  const script = scripts[queueItem.script] || scripts.winback;
  const lastProduct = customer.tags[0];

  return (
    <>
      <div className="page-header">
        <div>
          <h1>Telesale Console</h1>
          <div className="sub">{D.callQueue.length} cuộc gọi trong queue · Bạn đang ở mục {activeIdx + 1}/{D.callQueue.length}</div>
        </div>
        <div className="row gap-2">
          <button className="btn btn-secondary" onClick={() => window.tvsDemo('Lịch trình ca gọi')}><Icon name="calendar" size={14}/>Lịch trình</button>
          <button className="btn btn-secondary" onClick={() => window.tvsDemo('Thư viện scripts')}><Icon name="fileText" size={14}/>Tất cả scripts</button>
        </div>
      </div>

      {/* Call bar */}
      <div className="callbar mb-5">
        <div className="ph-status">
          {callState === 'active' && <span className="pulse"/>}
          {callState === 'calling' && <span className="status-dot amber" style={{width:12,height:12}}/>}
          {callState === 'idle' && <span className="status-dot grey" style={{width:12,height:12}}/>}
          {callState === 'wrap' && <span className="status-dot blue" style={{width:12,height:12}}/>}
          <div>
            <div style={{color:'rgba(255,255,255,0.7)',fontSize:11,letterSpacing:'0.12em',textTransform:'uppercase',fontWeight:700}}>
              {callState === 'idle' ? 'Sẵn sàng' : callState === 'calling' ? 'Đang kết nối...' : callState === 'active' ? 'Đang gọi' : 'Wrap-up'}
            </div>
            <div style={{color:'#fff',fontFamily:'var(--font-display)',fontWeight:700,fontSize:22}}>{customer.name}</div>
            <div style={{color:'rgba(255,255,255,0.6)',fontSize:13}} className="tnum">{customer.phone} · {customer.city}</div>
          </div>
        </div>
        <div className="timer">{formatTimer(duration)}</div>
        <div style={{flex:1}}/>
        <div className="row gap-2">
          {callState === 'active' && (
            <>
              <button className="btn btn-icon btn-secondary" style={{background:'rgba(255,255,255,0.10)',color:'#fff',borderColor:'transparent'}} onClick={() => setMuted(m=>!m)}>
                <Icon name={muted ? 'micOff' : 'mic'} size={18}/>
              </button>
              <button className="btn btn-icon btn-secondary" title="Giữ máy" style={{background:'rgba(255,255,255,0.10)',color:'#fff',borderColor:'transparent'}}
                onClick={() => window.tvsDemo('Giữ máy (hold)')}>
                <Icon name="pause" size={18}/>
              </button>
              <button className="btn btn-icon btn-secondary" title="Ghi chú nhanh" style={{background:'rgba(255,255,255,0.10)',color:'#fff',borderColor:'transparent'}}
                onClick={() => window.tvsDemo('Ghi chú trong cuộc gọi')}>
                <Icon name="note" size={18}/>
              </button>
            </>
          )}
          {callState === 'idle' && (
            <button className="btn btn-cta btn-lg" onClick={startCall}>
              <Icon name="phone" size={16}/>Bắt đầu gọi
            </button>
          )}
          {callState === 'calling' && (
            <button className="btn btn-danger btn-lg" onClick={() => setCallState('idle')}>
              <Icon name="close" size={16}/>Hủy
            </button>
          )}
          {callState === 'active' && (
            <button className="btn btn-danger btn-lg" onClick={endCall}>
              <Icon name="close" size={16}/>Kết thúc
            </button>
          )}
          {callState === 'wrap' && (
            <button className="btn btn-cta btn-lg" onClick={finishWrap} disabled={!outcome}>
              <Icon name="check" size={16}/>Lưu & Tiếp theo
            </button>
          )}
        </div>
      </div>

      <div className="grid" style={{gridTemplateColumns:'1fr 360px',gap:'var(--space-4)'}}>
        {/* LEFT — Customer context + script + wrap-up */}
        <div>
          {/* Customer context */}
          <Card pad={false} className="mb-4">
            <div style={{padding:'var(--space-4) var(--space-5)',display:'flex',gap:'var(--space-4)',alignItems:'center'}}>
              <Avatar name={customer.name} size="lg" tier={tierVariant(customer.tier)}/>
              <div style={{flex:1}}>
                <div className="row gap-2">
                  <h3 style={{margin:0,fontSize:'var(--t-lg)',color:'var(--fg-1)'}}>{customer.name}</h3>
                  <Tag variant={tierVariant(customer.tier)}>{customer.tier}</Tag>
                  {customer.tags.includes('At-risk') && <Tag variant="danger">Nguy cơ rời bỏ</Tag>}
                </div>
                <div className="text-sm fg-muted mt-1">
                  Khách {fmt.date(customer.joined).slice(3)} · {customer.orders} đơn · LTV <span className="strong" style={{color:'var(--fg-1)'}}>{fmt.vndFull(customer.ltv)}</span> · Lần mua cuối {fmt.rel(customer.lastOrder)}
                </div>
              </div>
              <button className="btn btn-secondary btn-sm" onClick={() => onOpenCustomer(customer)}>
                <Icon name="eye" size={14}/>Xem hồ sơ 360°
              </button>
            </div>
            <div className="divider"/>
            <div style={{padding:'var(--space-3) var(--space-5)',display:'grid',gridTemplateColumns:'repeat(4,1fr)',gap:'var(--space-3)'}}>
              <div>
                <div className="text-xs fg-muted">Sản phẩm thường mua</div>
                <div className="text-sm strong fg-1 mt-1">{customer.tags.slice(0,2).join(' · ')}</div>
              </div>
              <div>
                <div className="text-xs fg-muted">Đơn hàng gần nhất</div>
                <div className="text-sm strong fg-1 mt-1">{orders[0] ? fmt.vndFull(orders[0].total) : '—'}</div>
              </div>
              <div>
                <div className="text-xs fg-muted">Kênh ưa thích</div>
                <div className="text-sm strong fg-1 mt-1">{customer.preferredContact}</div>
              </div>
              <div>
                <div className="text-xs fg-muted">NPS lần cuối</div>
                <div className="text-sm strong fg-1 mt-1">{customer.nps ?? '—'}/10</div>
              </div>
            </div>
          </Card>

          {/* Script */}
          <Card pad={false} className="mb-4">
            <CardHeader title={script.title} sub={`Lý do gọi: ${queueItem.reason}`}
              actions={<Tag variant="info" dot>Đang ở: Mở đầu</Tag>}/>
            <div className="card-pad">
              {script.sections.map((s, i) => (
                <div key={i} style={{padding: 'var(--space-3) var(--space-4)', borderLeft: i===0 ? '3px solid var(--vs-light-blue)' : '3px solid var(--border-1)', background: i===0 ? 'rgba(65,182,230,0.06)' : 'transparent', borderRadius: 'var(--radius-sm)', marginBottom: 8}}>
                  <div className="row mb-2">
                    <div className="bold" style={{color: i===0 ? 'var(--vs-dark-blue)' : 'var(--fg-1)', fontSize:13}}>{i+1}. {s.h}</div>
                    {i===0 && <button className="btn btn-ghost btn-sm" style={{marginLeft:'auto'}} onClick={() => window.tvsDemo('Đánh dấu hoàn thành bước script')}><Icon name="check" size={12}/>Hoàn thành</button>}
                  </div>
                  <div className="text-sm" style={{whiteSpace:'pre-wrap',color: 'var(--fg-2)',lineHeight:1.6}}>
                    {s.body.replace('{name}', customer.name).replace('{agent}','Mỹ Linh').replace('{lastProduct}',lastProduct).replace('{category}', customer.tags[0])}
                  </div>
                </div>
              ))}
            </div>
          </Card>

          {/* Wrap-up */}
          {callState === 'wrap' && (
            <Card>
              <h3 style={{margin:'0 0 var(--space-3)',color:'var(--fg-1)',fontSize:'var(--t-md)'}}>Wrap-up — Kết quả cuộc gọi</h3>
              <div className="text-sm fg-muted mb-4">Chọn kết quả để cập nhật vào CRM. Thông tin này sẽ được dùng để tính KPI hôm nay.</div>
              <div style={{display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:8}} className="mb-4">
                {[
                  ['success','Bán thành công','check','#06A77D'],
                  ['callback','Đặt lịch lại','clock','#41B6E6'],
                  ['nointerest','Không quan tâm','close','#777'],
                  ['nopickup','Không nghe máy','phone','#777'],
                  ['wrong','Sai số','close','#BF0923'],
                  ['other','Khác','more','#777'],
                ].map(([k,l,ic,c]) => (
                  <button key={k}
                    onClick={() => setOutcome(k)}
                    className="btn btn-secondary"
                    style={{justifyContent:'flex-start',padding:'12px',borderColor: outcome===k ? c : 'var(--border-1)',background: outcome===k ? c+'10' : 'var(--bg-page)'}}>
                    <Icon name={ic} size={14} style={{color:c}}/>
                    <span style={{color: outcome===k ? c : 'var(--fg-2)',fontWeight: outcome===k ? 700 : 500}}>{l}</span>
                  </button>
                ))}
              </div>
              <div className="field-label">Ghi chú</div>
              <textarea className="textarea" placeholder="Tóm tắt nội dung cuộc gọi, follow-up cần làm..." value={note} onChange={(e)=>setNote(e.target.value)}/>
              {outcome === 'success' && (
                <div className="banner mt-3" style={{background:'rgba(6,167,125,0.10)',borderColor:'rgba(6,167,125,0.30)',color:'#055d44'}}>
                  <Icon name="cart" size={16}/>
                  <div style={{flex:1}}>
                    <div className="bold">Ghi nhận đơn hàng vừa chốt?</div>
                    <div className="text-xs">Lưu sản phẩm khách đã chốt vào lịch sử mua — đơn thực được tạo trên hệ thống bán hàng.</div>
                  </div>
                  <button className="btn btn-cta btn-sm" onClick={() => onLogOrder && onLogOrder(customer)}><Icon name="plus" size={12}/>Ghi nhận đơn</button>
                </div>
              )}
              {outcome === 'callback' && (
                <div className="row gap-3 mt-3">
                  <input className="input" type="datetime-local" value={callbackAt} onChange={(e) => setCallbackAt(e.target.value)} style={{flex:1}}/>
                  <span className="text-sm fg-muted">→ Lịch gọi lại sẽ được lưu vào tab Follow-up của khách</span>
                </div>
              )}
            </Card>
          )}
        </div>

        {/* RIGHT — Queue, recent orders, products */}
        <div>
          <Card pad={false} className="mb-4">
            <CardHeader title="Hàng đợi" sub={`${D.callQueue.length} cuộc · ${activeIdx+1} đã ở`}/>
            <div style={{padding:'var(--space-2)'}}>
              {D.callQueue.map((q, i) => (
                <button key={q.id}
                  onClick={() => setActiveIdx(i)}
                  style={{
                    display:'flex',width:'100%',alignItems:'center',gap:'var(--space-3)',
                    padding:'10px 12px',borderRadius:'var(--radius-md)',border:'none',background: i === activeIdx ? 'rgba(65,182,230,0.10)' : 'transparent',
                    cursor:'pointer',textAlign:'left',marginBottom:2,
                  }}>
                  <div style={{width:24,textAlign:'center',color:i < activeIdx ? 'var(--status-success)' : 'var(--fg-muted)'}}>
                    {i < activeIdx ? <Icon name="check" size={16}/> : <span className="tnum text-xs bold">{i+1}</span>}
                  </div>
                  <div style={{flex:1,minWidth:0}}>
                    <div className="strong text-sm" style={{color:'var(--fg-1)'}}>{q.name}</div>
                    <div className="text-xs fg-muted" style={{overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{q.scheduled} · {q.reason}</div>
                  </div>
                  <Tag variant={q.priority === 'Cao' ? 'danger' : q.priority === 'Trung bình' ? 'warning' : 'outline'}>{q.priority.slice(0,3)}</Tag>
                </button>
              ))}
            </div>
          </Card>

          <Card pad={false} className="mb-4">
            <CardHeader title="Đơn hàng gần đây" sub={`${orders.length} đơn`}/>
            <div className="card-pad">
              {orders.slice(0,3).map(o => (
                <div key={o.id} className="activity" style={{padding:'10px 0'}}>
                  <div className="ico"><Icon name="cart" size={14}/></div>
                  <div className="body">
                    <div className="title text-xs">{o.id}</div>
                    <div className="meta">{fmt.rel(o.date)} · {fmt.vndFull(o.total)}</div>
                  </div>
                </div>
              ))}
              {orders.length === 0 && <div className="text-xs fg-muted">Chưa có đơn hàng</div>}
            </div>
          </Card>

          <Card pad={false}>
            <CardHeader title="Gợi ý cross-sell" sub="Cho khách này"/>
            <div className="card-pad">
              {D.products.slice(4,7).map(p => (
                <div key={p.sku} className="row mb-3" style={{padding:'8px',border:'1px solid var(--border-1)',borderRadius:'var(--radius-sm)'}}>
                  <div style={{width:36,height:36,borderRadius:4,background:'var(--bg-soft)',display:'flex',alignItems:'center',justifyContent:'center',color:'var(--vs-light-blue)'}}>
                    <Icon name="pill" size={18}/>
                  </div>
                  <div style={{flex:1,minWidth:0}}>
                    <div className="text-xs strong fg-1" style={{overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{p.name}</div>
                    <div className="text-xs fg-muted">{fmt.vndFull(p.price)}</div>
                  </div>
                  <button className="btn btn-icon btn-sm btn-cta" title="Ghi nhận đơn với sản phẩm này"
                    onClick={() => onLogOrder && onLogOrder(customer)}><Icon name="plus" size={12}/></button>
                </div>
              ))}
            </div>
          </Card>
        </div>
      </div>
    </>
  );
}

window.TelesaleScreen = TelesaleScreen;
