// quotetab.jsx — 4 · 報價信（情境一/二/三） + 案件詳情外殼 CaseDetail

const SITU = [
  { id:'s1', label:'情境一 · 接受洽談', sub:'預設 · 報基礎價與規範' },
  { id:'s2', label:'情境二 · 婉拒', sub:'信件加註「婉拒」時' },
  { id:'s3', label:'情境三 · 團購＋稿費', sub:'加註「團購加稿費」時' },
];

// 全域範本：從 localStorage 讀取（第一次載入即就用較新範本）
function loadTemplate(situ){
  try { const t=JSON.parse(localStorage.getItem('gm_tmpl_'+situ)); return t||null; } catch(e){ return null; }
}
function saveTemplate(situ, body){
  localStorage.setItem('gm_tmpl_'+situ, JSON.stringify(body));
}
function resetTemplate(situ){
  localStorage.removeItem('gm_tmpl_'+situ);
}


function priceOf(key){ return (window.PRICE_LIST.find(p=>p.key===key)||{}).price||0; }
function itemName(key){ return (window.PRICE_LIST.find(p=>p.key===key)||{}).item||''; }

function genEmail(c){
  const q = c.quote;
  const greet = `${c.contact} 您好，`;
  const sign = `\n\nBest regards,\n多多`;
  const line = q.items.filter(k=>!k.startsWith('custom_')).map(k=>{
    const adj=(q.adjusts||{})[k]||0;
    const price=priceOf(k)+(adj||0);
    return '· '+itemName(k)+'　NT$ '+window.fmtNum(price);}).join('\n')+
    ((q.customItems||[]).filter(x=>q.items.includes('custom_'+x.id)).map(x=>'\n· '+x.name+'　NT$ '+window.fmtNum(x.price))).join('');
  const customTotal=(q.customItems||[]).filter(x=>q.items.includes('custom_'+x.id)).reduce((s,x)=>s+(+x.price||0),0);
  const base = q.items.filter(k=>!k.startsWith('custom_')).reduce((s,k)=>s+(priceOf(k)+((q.adjusts||{})[k]||0)),0)+customTotal;
  const subtotal = q.rush ? Math.round(base*1.5) : base;
  const lawNote = c.riskKind==='food'
    ? '\n＊本案產品涉保健訴求，文案將避開療效用語，依食品安全衛生管理法 §28 規範並揭露 #AD。'
    : c.riskKind==='cosmetic'
    ? '\n＊本案產品涉化粧品訴求，文案將避開醫療效能用語，依化粧品衛生安全管理法 §10 及認定準則規範並揭露 #AD。'
    : '';

  const tmpl = loadTemplate(q.situation);
  if(q.situation==='s2'){
    return { subject:`Re: ${c.product} 合作邀請 — ${c.vendor}`,
      body: tmpl || `${greet}\n\n我是多多，負責國美的合作洽談。非常感謝您的邀約與對國美的青睞！\n\n由於近期檔期已排定、此次產品方向與國美的內容調性較不相符，這次先不安排合作，還請見諒。未來若有合適的企劃，非常歡迎再與我們聯繫，也歡迎加入官方 LINE（@942njuhl）保持聯繫。\n\n再次感謝您的來信，祝順心順利。${sign}` };
  }
  if(q.situation==='s3'){
    return { subject:`Re: ${c.product} 團購合作 — ${c.vendor}`,
      body: tmpl || `${greet}\n\n我是多多，負責國美的合作洽談，感謝您的來信！除單篇合作外，國美亦可協助團購導購，以下為建議方案：\n\n【一、合作內容與報價（NT$ 未稅）】\n${line||'（請於左側勾選項目）'}\n小計：NT$ ${window.fmtNum(subtotal)}${q.rush?'（急件 ×1.5）':''}\n\n【二、團購方案】\n稿費：NT$ ${window.fmtNum(q.groupFee)}（涵蓋團購貼文／限動企劃與導購執行）\n分潤：實際成交金額之 ${q.share}%，月結。\n團購連結與優惠碼請於上線前 3 個工作天提供。\n\n【三、付款方式】\n訂金：簽訂委刊單後 7 日內 50%；尾款：驗收並收到發票後 30 日內 50%；團購分潤月結。\n\n【四、規範】\n大綱與成品各 1 次免費修改；依規定加註 #AD；保留創作者原創風格。${lawNote}\n\n後續歡迎加入官方 LINE：@942njuhl${sign}` };
  }
  // s1
  return { subject:`Re: ${c.product} 合作邀請 — ${c.vendor}`,
    body: tmpl || `${greet}\n\n我是多多，負責國美的合作洽談，感謝您的來信詢問。先提供基礎報價與合作規範給您參考～（報價可依後續產品與需求調整）\n\n【一、合作內容與報價（NT$ 未稅）】\n${line||'（請於左側勾選項目）'}\n小計：NT$ ${window.fmtNum(subtotal)}${q.rush?'（急件 ×1.5）':''}\n＊報價單發出 30 天內有效，所有報價皆會開立發票。\n\n【二、付款方式】\n訂金：簽訂委刊單後 7 日內支付 50%\n尾款：驗收完成並收到發票後 30 日內支付 50%\n\n【三、內容提案與修改規範】\n大綱與成品各 1 次免費修改（限相同主題方向）；內容提出後 7 天內未回覆視同驗收通過。\n\n【四、製作時程】\n短影音約 3–4 週、社群貼文約 2 週；製作期不足視為急件，報價調整為 1.5 倍。\n\n【五、版權與授權】\n敬請保留創作者原創風格；依規定加註 #AD；額外平台搬移／投放廣告須另計授權與廣告利用費。${lawNote}\n\n後續溝通歡迎加入官方 LINE：@942njuhl${sign}` };
}

function QuoteTab({ c, onUpdate, onSent, toast }){
  const q = c.quote;
  const setQ = (patch)=> onUpdate({ quote:{ ...q, ...patch } });
  const customItems = q.customItems||[];
  const toggleItem = (k)=> setQ({ items: q.items.includes(k)? q.items.filter(x=>x!==k): [...q.items, k] });
  const addCustomItem = ()=>{
    const id = Date.now();
    setQ({ customItems:[...customItems,{id,name:'',price:0}] });
  };
  const setCustom = (id,patch)=> setQ({ customItems:customItems.map(x=>x.id===id?{...x,...patch}:x) });
  const delCustom = (id)=> setQ({ customItems:customItems.filter(x=>x.id!==id), items:q.items.filter(k=>k!=='custom_'+id) });
  const adjusts = q.adjusts || {};
  const setAdj = (k, v)=> setQ({ adjusts: { ...adjusts, [k]: v } });
  const [adjMode, setAdjMode] = React.useState(false);
  const [aiLoading, setAiLoading] = React.useState(false);
  const runAIQuote = async () => {
    if (!c.email?.trim()) { toast('尚無廠商來信，無法 AI 撰寫'); return; }
    setAiLoading(true);
    try {
      const allItems = [
        ...q.items.filter(k=>!k.startsWith('custom_')).map(k=>({ name:itemName(k), fee:priceOf(k)+(adjusts[k]||0) })),
        ...customItems.filter(x=>q.items.includes('custom_'+x.id)).map(x=>({ name:x.name, fee:+x.price||0 }))
      ];
      const r = await window.generateQuoteWithAI(c, allItems, subtotal, q.situation);
      setQ({ subjectOverride:r.subject, bodyOverride:r.body });
      toast('✦ AI 報價信已產生');
    } catch(e) {
      if(e.message==='no-key'){ toast('請先設定 Gemini API 金鑰'); window.__openAISettings?.(); }
      else toast('AI 產生失敗：'+e.message);
    }
    setAiLoading(false);
  };
  const itemTotal = (k)=> priceOf(k) + (adjusts[k]||0);
  const base = q.items.filter(k=>!k.startsWith('custom_')).reduce((s,k)=>s+(priceOf(k)+(adjusts[k]||0)),0)
    + customItems.filter(x=>q.items.includes('custom_'+x.id)).reduce((s,x)=>s+(+x.price||0),0);
  const subtotal = q.rush? Math.round(base*1.5): base;
  const mail = genEmail(c);
  const subject = q.subjectOverride!=null ? q.subjectOverride : mail.subject;
  const body = q.bodyOverride!=null ? q.bodyOverride : mail.body;
  const edited = q.subjectOverride!=null || q.bodyOverride!=null;
  const copy = ()=>{ window.copyText(subject+'\n\n'+body, toast, '已複製報價信到剪貼簿'); };
  const resync = ()=>{ setQ({ subjectOverride:null, bodyOverride:null }); toast('已依範本重新產生報價信'); };

  return (
    <div className="tabwrap">
      <div className="tabbody">
        <div style={{ display:'grid', gridTemplateColumns:'300px 1fr', gap:18 }}>
          {/* controls */}
          <div>
            <div className="sectlbl">選擇情境</div>
            <div style={{ display:'flex', flexDirection:'column', gap:8, marginBottom:16 }}>
              {SITU.map(s=>(
                <div key={s.id} className={'situ'+(q.situation===s.id?' on':'')} onClick={()=>setQ({situation:s.id})}>
                  <span className="radio"></span>
                  <div><div style={{fontSize:12.5,fontWeight:600}}>{s.label}</div>
                  <div className="faint" style={{fontSize:10.5}}>{s.sub}</div></div>
                </div>
              ))}
            </div>
            {q.situation!=='s2' && <>
              <div className="sectlbl" style={{display:'flex',alignItems:'center',gap:8}}>
                勾選合作項目
                <button className={'linkbtn adjbtn'+(adjMode?' on':'')} onClick={()=>setAdjMode(v=>!v)}>{adjMode?'✓ 定稿調整中':'✎ 定稿調整模式'}</button>
              </div>
              <div style={{ display:'flex', flexDirection:'column', gap:2, marginBottom:12 }}>
                {window.PRICE_LIST.map(p=>{
                  const checked=q.items.includes(p.key);
                  const adj=adjusts[p.key]||0;
                  return (
                  <div key={p.key} className="itemrowwrap">
                    <label className={'itemrow'+(checked?' on':'')} style={{flex:1}}>
                      <input type="checkbox" checked={checked} onChange={()=>toggleItem(p.key)} />
                      <span className="ell" style={{flex:1,fontSize:11.5}}>{p.item}</span>
                    <span className="mono faint" style={{fontSize:11}}>{window.fmtNum(adj?itemTotal(p.key):p.price)}</span>
                    </label>
                    {adjMode && checked && (
                      <div className="adjrow">
                        <span className="faint" style={{fontSize:10}}>±調整</span>
                        <input className="adjinp" type="number" value={adj} placeholder="0"
                          onChange={e=>setAdj(p.key,+e.target.value)}
                          onClick={e=>e.stopPropagation()} />
                        <span className="faint" style={{fontSize:10}}>→ NT$ {window.fmtNum(itemTotal(p.key))}</span>
                        {adj!==0 && <button className="linkbtn" style={{fontSize:10}} onClick={()=>setAdj(p.key,0)}>×</button>}
                      </div>
                    )}
                  </div>);
                })}
              </div>
              <label className="chk" style={{marginBottom:12}}>
                <input type="checkbox" checked={q.rush} onChange={e=>setQ({rush:e.target.checked})} />急件（製作期不足，報價 ×1.5）
              </label>
              {q.situation==='s3' && (
                <div className="card" style={{padding:'12px 13px', marginBottom:12, background:'var(--surface-2)'}}>
                  <div className="sectlbl" style={{marginBottom:8}}>團購參數</div>
                  <div style={{display:'flex',gap:9}}>
                    <div style={{flex:1}}><div className="faint" style={{fontSize:10,marginBottom:4}}>稿費 NT$</div>
                      <input className="inp" type="number" value={q.groupFee} onChange={e=>setQ({groupFee:+e.target.value})} /></div>
                    <div style={{width:84}}><div className="faint" style={{fontSize:10,marginBottom:4}}>分潤 %</div>
                      <input className="inp" type="number" value={q.share} onChange={e=>setQ({share:+e.target.value})} /></div>
                  </div>
                </div>
              )}
              <div className="card subtotal">
                <span className="faint" style={{fontSize:11}}>小計（未稅）{q.rush&&' · 含急件加成'}</span>
                <span className="serif mono" style={{fontSize:21,fontWeight:700}}>{window.fmt(subtotal)}</span>
              </div>
              {/* 自訂項目 */}
              {customItems.map(x=>(
                <div key={x.id} className="custrow">
                  <input className="miniinp" style={{flex:1}} placeholder="項目名稱" value={x.name} onChange={e=>setCustom(x.id,{name:e.target.value})} />
                  <input className="miniinp mono" style={{width:80}} type="number" placeholder="金額" value={x.price||''} onChange={e=>setCustom(x.id,{price:+e.target.value})} />
                  <input type="checkbox" checked={q.items.includes('custom_'+x.id)} onChange={()=>toggleItem('custom_'+x.id)} title="勾選入報價" />
                  <button className="linkbtn" style={{color:'var(--rose-ink)'}} onClick={()=>delCustom(x.id)}>×</button>
                </div>
              ))}
              <button className="btn" style={{height:28,fontSize:11.5,marginTop:4}} onClick={addCustomItem}>＋ 新增項目</button>
            </>}
          </div>
          {/* preview */}
          <div>
            <div className="sectlbl" style={{display:'flex',alignItems:'center',gap:8}}>
              報價信預覽
              <span className="faint" style={{fontSize:10,fontWeight:400}}>（可直接點入編修）</span>
              {edited && <span className="pill risk-mid" style={{height:18,fontSize:9.5}}><span className="dot"></span>已手動編修</span>}
              {edited && <button className="linkbtn" onClick={resync}>↺ 重新依範本產生</button>}
              <button className="linkbtn" style={{marginLeft:'auto'}} onClick={()=>{ saveTemplate(q.situation, body); toast('已儲存為新範本·後續案件自動帶入'); }}>✓ 儲存為新範本</button>
              {loadTemplate(q.situation) && <button className="linkbtn" style={{color:'var(--rose-ink)'}} onClick={()=>{ resetTemplate(q.situation); resync(); toast('已恢復預設範本'); }}>↺ 恢復預設</button>}
            </div>
            <div className="card" style={{ padding:0, overflow:'hidden' }}>
              <div className="mailhead">
                <span className="faint mono" style={{fontSize:10}}>主旨</span>
                <input className="mailsubin" value={subject} onChange={e=>setQ({subjectOverride:e.target.value})} />
                <span className="pill risk-low" style={{marginLeft:'auto',height:19,fontSize:10,flex:'none'}}>{edited?'自訂內容':'已套用範本規範'}</span>
              </div>
              <textarea className="emailedit" value={body} onChange={e=>setQ({bodyOverride:e.target.value})} spellCheck={false} />
            </div>
          </div>
        </div>
      </div>
      <div className="tabfoot">
        <button className="btn" onClick={copy}>⧉ 複製內文</button>
        <button className="btn" onClick={()=>toast('已存草稿')}>儲存草稿</button>
        <window.AIBtn onClick={runAIQuote} loading={aiLoading}>✦ AI 撰寫報價信</window.AIBtn>
        <button className="btn primary" style={{ marginLeft:'auto' }} onClick={onSent}>報價信已寄發 ✓</button>
      </div>
    </div>
  );
}

/* ---------------- 案件詳情外殼 ---------------- */
function CaseDetail({ c, tab, setTab, onUpdate, onClose, onMove, onSchedule, toast }){
  const { Av, Pill } = window;
  const dead = c.progress==='未成交' || c.progress==='婉拒' || c.willing==='婉拒';
  const TABS = dead ? window.DETAIL_TABS.filter(t=>t.grp!=='deal') : window.DETAIL_TABS;
  const vtab = TABS.some(t=>t.id===tab) ? tab : TABS[0].id;
  let idx = TABS.findIndex(t=>t.id===vtab);
  if(idx<0) idx = 0;
  const goNext = ()=> setTab(TABS[Math.min(TABS.length-1, idx+1)].id);
  return (
    <div className="viewcol">
      <div className="dethead">
        <button className="iconbtn" onClick={onClose} title="返回看板">←</button>
        <Av bg={c.avatarBg} size={36}>{c.vendor.slice(0,1)}</Av>
        <div>
          <div className="serif" style={{ fontSize:16, fontWeight:700 }}>{c.vendor} · {c.product}</div>
          <div className="faint" style={{ fontSize:11 }}>窗口 {c.contact} · <span className="mono">{c.id}</span> · {window.stageName(c.stage)}</div>
        </div>
        <div style={{ marginLeft:'auto', display:'flex', alignItems:'center', gap:9 }}>
          <Pill tone={window.riskTone(c.risk)} style={{height:22}}>{c.riskLabel}</Pill>
        </div>
      </div>
      <div className="dettabs">
        {TABS.map((t,ti)=>{
          const done = TABS.findIndex(x=>x.id===t.id) < idx;
          const on = t.id===vtab;
          const showDiv = t.grp==='deal' && TABS[ti-1] && TABS[ti-1].grp!=='deal';
          return (
            <React.Fragment key={t.id}>
              {showDiv && <div className="tabdiv"><span>成交後</span></div>}
              <div className={'dtab'+(on?' on':'')} onClick={()=>setTab(t.id)}>
              <span className="dtabn" style={{ background: done?'var(--sage)':on?'var(--clay)':'var(--surface-2)',
                color:(done||on)?'#fff':'var(--ink-3)', border:'1px solid '+((done||on)?'transparent':'var(--line-2)') }}>{done?'✓':t.n}</span>
              {t.label}
            </div>
            </React.Fragment>
          );
        })}
      </div>
      <div className="detbody">
        {vtab==='mail'   && <window.MailTab   c={c} onUpdate={onUpdate} onNext={goNext} toast={toast} />}
        {vtab==='risk'   && <window.RiskTab   c={c} onUpdate={onUpdate} onNext={goNext} toast={toast} />}
        {vtab==='intent' && <window.IntentTab c={c} onUpdate={onUpdate} onNext={goNext} toast={toast} />}
        {vtab==='quote'  && <QuoteTab c={c} onUpdate={onUpdate} toast={toast} onSent={()=>{ const now=new Date(); const d=`${now.getFullYear()}/${String(now.getMonth()+1).padStart(2,'0')}/${String(now.getDate()).padStart(2,'0')}`; onUpdate({ quoteSentDate:d, stage: (c.stage==='inquiry'||c.stage==='intent')?'quote':c.stage, progress: (c.progress==='洽談'||c.progress==='意願')?'報價':c.progress }); toast('已記錄報價信寄發日期：'+d); }} />}
        {vtab==='io'     && <window.InsertionOrderTab c={c} onUpdate={onUpdate} onNext={goNext} onMove={onMove} toast={toast} />}
        {vtab==='comm'   && <window.CommTab c={c} onUpdate={onUpdate} onNext={goNext} toast={toast} />}
        {vtab==='prod'   && <window.ProdScheduleTab c={c} onUpdate={onUpdate} onMove={onMove} toast={toast} />}
      </div>
    </div>
  );
}

window.CaseDetail = CaseDetail;
