/* ============================================================
   案件 新規／編集 フォーム（手動起票 + スクレイピング起票の差分）
   ============================================================ */
function CaseFormModal({ editCase, onClose, initialStatus, initialTitle, onSaved }) {
  const { saveCaseForm, cases, workspaceId, defaultWorkspaceId } = useStore();
  const D = window.APP_DATA;
  // カテゴリ候補＝マスタ候補 ∪ 既存案件で使用中の値（自由入力した独自カテゴリも候補に出る）
  const catOptions = Array.from(new Set([...(D.CATEGORIES || []), ...cases.flatMap(k => k.categories || [])]));
  const [business,setBusiness] = React.useState(editCase ? ASM_WORKSPACES.idOf(editCase) : workspaceId === 'all' ? defaultWorkspaceId : workspaceId);
  const [busy,setBusy] = React.useState(false), [error,setError] = React.useState('');
  const isEdit = !!editCase;
  const isScraped = isEdit && editCase.source === 'scrape';
  const [title, setTitle] = React.useState(editCase ? editCase.title : (initialTitle || ''));
  const [customerId, setCustomerId] = React.useState(editCase ? editCase.customerId : ((D.customers.find(c => !c.mergedInto) || {}).id || ''));
  const [custOpen, setCustOpen] = React.useState(false);
  const [custQ, setCustQ] = React.useState('');
  const [body, setBody] = React.useState(editCase ? editCase.body : '');
  const [ownerId, setOwnerId] = React.useState(editCase ? editCase.ownerId : null);
  const [subIds, setSubIds] = React.useState(editCase ? editCase.subIds : []);
  // 新規時の期限は「今日 + 14日」を既定に（ハードコード日付だと過去になるため）
  const [due, setDue] = React.useState(editCase ? editCase.due : (() => { const d = new Date(); d.setDate(d.getDate() + 14); const p = (n) => String(n).padStart(2, '0'); return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`; })());
  const [status, setStatus] = React.useState(editCase ? editCase.status : (initialStatus || 'new'));
  const [note, setNote] = React.useState(editCase ? editCase.note : '');
  const [categories, setCategories] = React.useState(editCase ? (editCase.categories || []) : []);
  const [assignOpen, setAssignOpen] = React.useState(false);
  const [newCust, setNewCust] = React.useState(false);
  const custRef = React.useRef(null); const assignRef = React.useRef(null);
  React.useEffect(() => {
    const h = (e) => { if (custRef.current && !custRef.current.contains(e.target)) setCustOpen(false); if (assignRef.current && !assignRef.current.contains(e.target)) setAssignOpen(false); };
    document.addEventListener('mousedown', h); return () => document.removeEventListener('mousedown', h);
  }, []);
  const cust = D.customer(customerId);
  const owner = ownerId ? D.user(ownerId) : null;
  const custList = D.customers.filter(c => !c.mergedInto && (c.company.includes(custQ) || c.shortName.includes(custQ)));

  const submit = async () => {
    if (busy || !title.trim() || !customerId || !ownerId) return;
    setBusy(true);setError('');
    try {
      const savedId = await saveCaseForm({id:editCase?.id,title,customerId,body,ownerId,subIds,due,status,note,categories,workspaceId:business});
      if (onSaved && savedId) onSaved(savedId);onClose();
    } catch(e) {setError(e.message);} finally {setBusy(false);}
  };

  const Lock = () => <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 12, fontWeight: 600, color: '#9aa1ab', background: '#f0f1f4', padding: '2px 7px', borderRadius: 5, marginLeft: 8 }}><Icon name="link" size={11} stroke={2} />{t('cf.lock')}</span>;

  return (
    <Modal open onClose={busy?()=>{}:onClose} title={isEdit ? t('cf.editTitle') : t('cf.createTitle')} width={620}
      subtitle={isScraped ? t('cf.scrapedSubtitle') : (isEdit ? t('cf.editSubtitle') : t('cf.createSubtitle'))}
      footer={<><Button variant="subtle" disabled={busy} onClick={onClose}>{t('btn.cancel')}</Button><Button variant="primary" icon="check" onClick={submit} disabled={busy || !title.trim() || !customerId || !ownerId}>{isEdit ? t('btn.update') : t('btn.create')}</Button></>}>

      {error && <div role="alert" className="asm-error">{error}</div>}
      <Field label={window.t("ws.label")} required hint={isEdit ? window.t("extra.form.moveWorkspace") : undefined}><WorkspaceSelect value={business} onChange={setBusiness} disabled={isEdit}/></Field>
      {isScraped && (
        <div style={{ display: 'flex', gap: 10, padding: '11px 13px', background: '#f6f6fe', border: '1px solid #e4e3fb', borderRadius: 10, marginBottom: 18 }}>
          <Icon name="refresh" size={16} stroke={2} style={{ color: '#4a5af0', flex: '0 0 auto', marginTop: 1 }} />
          <div style={{ fontSize: 12, color: '#5b54b8', lineHeight: 1.55 }}>
            <span style={{ fontFamily: 'var(--mono)', fontWeight: 600 }}>{editCase.sourceNo}</span> · {t('cf.scrapedInfo')}
          </div>
        </div>
      )}

      <Field label={t('cf.fieldTitle')} required hint={isScraped ? t('cf.titleHint') : undefined}>
        <TextInput value={title} onChange={(e) => setTitle(e.target.value)} placeholder={t('cf.titlePlaceholder')} />
      </Field>

      {isScraped && (
        <React.Fragment>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(150px, 1fr))', gap: 14 }}>
            <Field label={<span>{t('cf.originalTitle')}<Lock /></span>}>
              <div style={{ ...inputStyle, background: '#f6f7fa', color: '#6b727c', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{editCase.originalTitle || title}</div>
            </Field>
            <Field label={<span>{t('cf.source')}<Lock /></span>}>
              <div style={{ ...inputStyle, background: '#f6f7fa', color: '#6b727c', display: 'flex', alignItems: 'center', gap: 7 }}>
                <Icon name="refresh" size={14} stroke={2} style={{ color: '#4a5af0' }} />{editCase.sourceName}
              </div>
            </Field>
          </div>
          <Field label={<span>{t('cf.sourceUrl')}<Lock /></span>}>
            <div style={{ ...inputStyle, background: '#f6f7fa', display: 'flex', alignItems: 'center', gap: 8, padding: '8px 10px 8px 12px' }}>
              <Icon name="link" size={14} stroke={2} style={{ color: '#9aa1ab', flex: '0 0 auto' }} />
              <a href={editCase.sourceUrl} target="_blank" rel="noreferrer" style={{ flex: 1, minWidth: 0, fontSize: 12.5, fontFamily: 'var(--mono)', color: '#4a5af0', textDecoration: 'none', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{editCase.sourceUrl}</a>
              <a href={editCase.sourceUrl} target="_blank" rel="noreferrer" style={{ flex: '0 0 auto' }}><Button variant="default" size="sm" icon="link">{t('btn.open')}</Button></a>
            </div>
          </Field>
        </React.Fragment>
      )}

      {/* 顧客（既存検索 or 新規） */}
      <Field label={t('cf.customer')} required hint={isScraped ? t('cf.customerScrapedHint') : t('cf.customerHint')}>
        <div ref={custRef} style={{ position: 'relative' }}>
          <button onClick={() => setCustOpen(o => !o)} style={{ ...inputStyle, display: 'flex', alignItems: 'center', justifyContent: 'space-between', cursor: 'pointer', textAlign: 'left' }}>
            {cust ? (
              <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <span style={{ fontSize: 12, fontWeight: 700, color: '#4a5af0', background: '#eef0fe', padding: '2px 7px', borderRadius: 5 }}>{cust.shortName}</span>
                <span style={{ fontWeight: 500 }}>{cust.company}</span>
              </span>
            ) : (
              <span style={{ color: '#9aa1ab', fontWeight: 500 }}>{window.t("extra.form.selectCustomer")}</span>
            )}
            <Icon name="chevronDown" size={15} stroke={2} style={{ color: '#b4bac3' }} />
          </button>
          {custOpen && (
            <div style={{ position: 'absolute', top: 44, left: 0, right: 0, zIndex: 60, background: '#fff', borderRadius: 10, border: '1px solid #e6e8ec', boxShadow: '0 14px 34px rgba(20,22,40,.16)', overflow: 'hidden' }}>
              <div style={{ padding: 9, borderBottom: '1px solid #f0f1f4' }}>
                <input autoFocus value={custQ} onChange={(e) => setCustQ(e.target.value)} placeholder={t('cf.customerSearch')} style={{ ...inputStyle, padding: '7px 10px', fontSize: 13 }} />
              </div>
              <div style={{ maxHeight: 200, overflowY: 'auto', padding: 6 }}>
                {custList.map(c => (
                  <div key={c.id} className="row-hover" onClick={() => { setCustomerId(c.id); setCustOpen(false); setCustQ(''); }} style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '8px 9px', borderRadius: 7, cursor: 'pointer' }}>
                    <span style={{ fontSize: 12, fontWeight: 700, color: '#4a5af0', background: '#eef0fe', padding: '2px 7px', borderRadius: 5 }}>{c.shortName}</span>
                    <span style={{ fontSize: 13, color: '#2b2f38' }}>{c.company}</span>
                  </div>
                ))}
                <div className="row-hover" onClick={() => { setNewCust(true); setCustOpen(false); }}
                  style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '9px', borderRadius: 7, cursor: 'pointer', color: '#4a5af0', fontWeight: 600, fontSize: 13, borderTop: '1px solid #f4f5f7', marginTop: 4 }}>
                  <Icon name="plus" size={15} stroke={2} />{t('cf.createNewCustomer', { name: custQ || t('cf.newCustomerFallback') })}
                </div>
              </div>
            </div>
          )}
        </div>
      </Field>

      {/* 担当（主必須 + 副複数可） */}
      <Field label={t('cf.owner')} required hint={t('cf.ownerHint')}>
        <div ref={assignRef} style={{ position: 'relative' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', minHeight: 38, padding: '5px 8px', border: '1px solid #dfe2e8', borderRadius: 8 }}>
            {owner && <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, background: '#eef0fe', borderRadius: 999, padding: '3px 9px 3px 3px' }}><Avatar user={owner} size={20} /><span style={{ fontSize: 12, fontWeight: 600, color: '#4a5af0' }}>{owner.short}</span><span style={{ fontSize: 12, color: '#9089d6' }}>{t('cf.mainOwner')}</span></span>}
            {subIds.map(id => { const u = D.user(id); return <span key={id} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, background: '#f4f5f7', borderRadius: 999, padding: '3px 9px 3px 3px' }}><Avatar user={u} size={20} /><span style={{ fontSize: 12, color: '#3b414b' }}>{u.short}</span><span style={{ fontSize: 12, color: '#9aa1ab' }}>{t('cf.subOwner')}</span></span>; })}
            <button onClick={() => setAssignOpen(o => !o)} style={{ display: 'inline-flex', alignItems: 'center', gap: 5, border: '1px dashed #cfd4db', borderRadius: 999, padding: '4px 11px', background: '#fff', cursor: 'pointer', fontFamily: 'inherit', fontSize: 12, color: '#7b828d', fontWeight: 600 }}>
              <Icon name="plus" size={13} stroke={2} />{t('cf.addOwner')}
            </button>
          </div>
          {assignOpen && (
            <div style={{ position: 'absolute', top: 46, left: 0, zIndex: 60, width: 280, background: '#fff', borderRadius: 12, border: '1px solid #e6e8ec', boxShadow: '0 14px 34px rgba(20,22,40,.16)', overflow: 'hidden' }}>
              <div style={{ padding: '8px 12px', fontSize: 12, color: '#9aa1ab', fontWeight: 700, borderBottom: '1px solid #f0f1f4' }}>{t('cf.ownerSelectHint')}</div>
              <div style={{ maxHeight: 240, overflowY: 'auto', padding: 6 }}>
                {D.users.map(u => {
                  const isO = ownerId === u.id; const isS = subIds.includes(u.id);
                  return (
                    <div key={u.id} className="row-hover" onClick={() => {
                      if (!ownerId || (!isO && !isS && !ownerId)) { setOwnerId(u.id); }
                      else if (isO) { setOwnerId(null); }
                      else if (isS) { setSubIds(subIds.filter(s => s !== u.id)); }
                      else if (!ownerId) { setOwnerId(u.id); }
                      else { setSubIds([...subIds, u.id]); }
                    }} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '7px 8px', borderRadius: 8, cursor: 'pointer' }}>
                      <Avatar user={u} size={28} />
                      <div style={{ flex: 1 }}><div style={{ fontSize: 13, fontWeight: 600, color: '#262b34' }}>{u.name}</div><div style={{ fontSize: 12, color: '#9aa1ab' }}>{ROLE_LABEL[u.role] || t('role.member')}</div></div>
                      {isO && <span style={{ fontSize: 12, fontWeight: 700, color: '#4a5af0', background: '#eef0fe', padding: '2px 7px', borderRadius: 5 }}>{t('cf.mainOwner')}</span>}
                      {isS && <span style={{ fontSize: 12, fontWeight: 700, color: '#0891b2', background: '#e0f4f8', padding: '2px 7px', borderRadius: 5 }}>{t('cf.subOwner')}</span>}
                    </div>
                  );
                })}
              </div>
            </div>
          )}
        </div>
      </Field>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(150px, 1fr))', gap: 14 }}>
        <Field label={t('cf.dueDate')}><TextInput type="date" value={due} onChange={(e) => setDue(e.target.value)} /></Field>
        <Field label={t('cf.status')}>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {D.STATUS_ORDER.map(s => (
              <button key={s} onClick={() => setStatus(s)} style={{ border: '1px solid ' + (status === s ? D.STATUS[s].color : '#e2e5ea'), background: status === s ? D.STATUS[s].soft : '#fff',
                borderRadius: 7, padding: '6px 10px', cursor: 'pointer', fontFamily: 'inherit', fontSize: 12, fontWeight: 600, color: status === s ? D.STATUS[s].fg : '#7b828d' }}>{D.STATUS[s].label}</button>
            ))}
          </div>
        </Field>
      </div>

      <Field label={window.t("cd.category")} hint={window.t("extra.form.categoryHint")}>
        <CategoryTags value={categories} onChange={setCategories} editable options={catOptions} />
      </Field>

      <Field label={<span>{t('cf.body')}{isScraped && <Lock />}</span>}>
        {isScraped ? (
          <div style={{ ...inputStyle, background: '#f6f7fa', color: '#6b727c', minHeight: 70, lineHeight: 1.65, fontSize: 12.5, whiteSpace: 'pre-wrap' }}>{body}</div>
        ) : (
          <textarea value={body} onChange={(e) => setBody(e.target.value)} rows={3} placeholder={t('cf.bodyPlaceholder')} style={{ ...inputStyle, resize: 'vertical', lineHeight: 1.6 }} />
        )}
      </Field>
      <Field label={t('cf.note')}>
        <textarea value={note} onChange={(e) => setNote(e.target.value)} rows={2} placeholder={t('cf.notePlaceholder')} style={{ ...inputStyle, resize: 'vertical', lineHeight: 1.6 }} />
      </Field>
      {newCust && (
        <CustomerFormModal initialCompany={custQ}
          onClose={() => setNewCust(false)}
          onSaved={(id) => { setCustomerId(id); setCustQ(''); setNewCust(false); }} />
      )}
    </Modal>
  );
}
Object.assign(window, { CaseFormModal });
