/* Templates View */
(function () {
  const { useState, useMemo, useRef, useEffect } = React;
  const { uid, renderTemplate, TEMPLATE_KIND_LABELS, AVAILABLE_VARS } = window.AppStore;
  const { Modal, showToast, Field } = window.Common;

  const EMPTY_TEMPLATE = () => ({
    id: '',
    name: '新しいテンプレート',
    kind: 'custom',
    subject: '',
    body: '',
  });

  function TemplatesView({ state, onChange }) {
    const [selectedId, setSelectedId] = useState(state.templates[0]?.id || '');
    const [confirmDelete, setConfirmDelete] = useState(null);
    const [previewConcertId, setPreviewConcertId] = useState('');
    const [previewEventId, setPreviewEventId] = useState('');
    const [lastFocused, setLastFocused] = useState('body');
    const subjectRef = useRef(null);
    const bodyRef = useRef(null);
    const pendingCursorRef = useRef(null);

    const selected = state.templates.find((t) => t.id === selectedId) || null;

    useEffect(() => {
      if (pendingCursorRef.current !== null) {
        const { field, pos } = pendingCursorRef.current;
        const el = field === 'subject' ? subjectRef.current : bodyRef.current;
        if (el) {
          el.focus();
          el.setSelectionRange(pos, pos);
        }
        pendingCursorRef.current = null;
      }
    });

    function setTemplateField(key, val) {
      const templates = state.templates.map((t) =>
        t.id === selectedId ? { ...t, [key]: val } : t
      );
      onChange({ ...state, templates });
    }

    function addTemplate() {
      const t = EMPTY_TEMPLATE();
      t.id = uid('t');
      const templates = [...state.templates, t];
      onChange({ ...state, templates });
      setSelectedId(t.id);
    }

    function copyTemplate() {
      if (!selected) return;
      const t = { ...selected, id: uid('t'), name: selected.name + ' (コピー)' };
      const templates = [...state.templates, t];
      onChange({ ...state, templates });
      setSelectedId(t.id);
    }

    function deleteTemplate(id) {
      const templates = state.templates.filter((t) => t.id !== id);
      onChange({ ...state, templates });
      setSelectedId(templates[0]?.id || '');
      setConfirmDelete(null);
      showToast('削除しました');
    }

    // Preview context
    const previewConcert = state.events.find((e) => e.id === previewConcertId) || state.events[0] || null;
    const previewEvent = previewEventId
      ? state.concerts.find((c) => c.id === previewEventId)
      : state.concerts.filter((c) => c.eventId === previewConcert?.id)[0] || null;
    const previewFlyer = previewConcert && previewEvent
      ? previewConcert.flyers.find((f) => f.id === previewEvent.flyerId) || previewConcert.flyers[0]
      : null;

    const preview = useMemo(() => {
      if (!selected || !previewConcert) return null;
      return renderTemplate(selected, { event: previewConcert, concert: previewEvent || {}, flyer: previewFlyer || {} });
    }, [selected, previewConcert, previewEvent, previewFlyer]);

    function copyToClipboard() {
      if (!preview) return;
      const text = '件名: ' + preview.subject + '\n\n' + preview.body;
      navigator.clipboard.writeText(text).then(() => showToast('コピーしました', 'success'));
    }

    function openMailto() {
      if (!preview || !previewEvent?.contactEmail) { showToast('先方のメールアドレスが未設定です', 'warn'); return; }
      const mailto = 'mailto:' + encodeURIComponent(previewEvent.contactEmail)
        + '?subject=' + encodeURIComponent(preview.subject)
        + '&body=' + encodeURIComponent(preview.body);
      window.open(mailto, '_blank');
    }

    function insertVar(varName) {
      const text = '{{' + varName + '}}';
      if (!selected) return;
      const field = lastFocused;
      const el = field === 'subject' ? subjectRef.current : bodyRef.current;
      if (!el) return;
      const start = el.selectionStart ?? el.value.length;
      const end = el.selectionEnd ?? el.value.length;
      const newVal = el.value.slice(0, start) + text + el.value.slice(end);
      setTemplateField(field, newVal);
      pendingCursorRef.current = { field, pos: start + text.length };
    }

    return (
      <div>
        <div className="page-header">
          <h1 className="page-title">メールテンプレート</h1>
        </div>
        <div className="templates-layout">
          {/* Template List */}
          <div className="template-list">
            <div className="template-list-header">
              テンプレート
              <button className="btn btn-primary btn-sm" onClick={addTemplate}>+</button>
            </div>
            {state.templates.length === 0 ? (
              <div style={{ padding: 16, fontSize: 13, color: 'var(--muted)' }}>テンプレートなし</div>
            ) : state.templates.map((t) => (
              <div
                key={t.id}
                className={'template-list-item' + (t.id === selectedId ? ' active' : '')}
                onClick={() => setSelectedId(t.id)}
              >
                <div className="template-item-name">{t.name}</div>
                <div className="template-item-kind">{TEMPLATE_KIND_LABELS[t.kind] || t.kind}</div>
              </div>
            ))}
          </div>

          {/* Editor */}
          {selected ? (
            <div className="template-editor">
              <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8, marginBottom: 16 }}>
                <button className="btn btn-secondary btn-sm" onClick={copyTemplate}>コピー</button>
                <button className="btn btn-danger btn-sm" onClick={() => setConfirmDelete(selected)}>削除</button>
              </div>

              <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                <Field label="テンプレート名">
                  <input value={selected.name} onChange={(e) => setTemplateField('name', e.target.value)} />
                </Field>
                <Field label="種別">
                  <select value={selected.kind} onChange={(e) => setTemplateField('kind', e.target.value)}>
                    {Object.entries(TEMPLATE_KIND_LABELS).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
                  </select>
                </Field>
                <Field label="件名">
                  <input
                    ref={subjectRef}
                    value={selected.subject}
                    onChange={(e) => setTemplateField('subject', e.target.value)}
                    onFocus={() => setLastFocused('subject')}
                    placeholder="件名"
                  />
                </Field>
                <Field label="本文">
                  <textarea
                    ref={bodyRef}
                    value={selected.body}
                    onChange={(e) => setTemplateField('body', e.target.value)}
                    onFocus={() => setLastFocused('body')}
                    rows={10}
                  />
                </Field>
              </div>

              {/* Variables */}
              <div style={{ marginTop: 16 }}>
                <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--muted)', marginBottom: 4 }}>
                  使用可能な変数
                </div>
                <div style={{ fontSize: 11, color: 'var(--muted)', marginBottom: 6 }}>
                  件名・本文にカーソルを置いてからクリックすると、その位置に挿入されます
                </div>
                <div className="var-badges">
                  {AVAILABLE_VARS.map((v) => (
                    <span key={v.name} className="var-badge" title={'{{' + v.name + '}}'} onClick={() => insertVar(v.name)}>{v.label}</span>
                  ))}
                </div>
              </div>

              {/* Preview */}
              <div className="template-preview">
                <div style={{ fontWeight: 700, fontSize: 14, color: 'var(--muted)', marginBottom: 12 }}>プレビュー</div>
                <div className="preview-controls">
                  <select
                    value={previewConcertId}
                    onChange={(e) => { setPreviewConcertId(e.target.value); setPreviewEventId(''); }}
                    style={{ width: 'auto', minWidth: 140 }}
                  >
                    {state.events.map((ev) => <option key={ev.id} value={ev.id}>{ev.title}</option>)}
                  </select>
                  <select
                    value={previewEventId}
                    onChange={(e) => setPreviewEventId(e.target.value)}
                    style={{ width: 'auto', minWidth: 160 }}
                  >
                    {state.concerts
                      .filter((c) => !previewConcertId || c.eventId === previewConcertId)
                      .map((c) => <option key={c.id} value={c.id}>{c.eventName}</option>)
                    }
                  </select>
                </div>
                {preview ? (
                  <>
                    <div className="preview-subject">件名: {preview.subject}</div>
                    <div className="preview-body">{preview.body}</div>
                    <div style={{ display: 'flex', gap: 8, marginTop: 14 }}>
                      <button className="btn btn-secondary btn-sm" onClick={copyToClipboard}>📋 クリップボードにコピー</button>
                      <button className="btn btn-secondary btn-sm" onClick={openMailto}>✉ メール起動</button>
                    </div>
                  </>
                ) : (
                  <div style={{ fontSize: 13, color: 'var(--muted)' }}>コンサート・イベントを選択してください</div>
                )}
              </div>
            </div>
          ) : (
            <div className="empty-state">
              <div className="empty-state-icon">✉️</div>
              <div className="empty-state-text">テンプレートを選択または作成してください</div>
            </div>
          )}
        </div>

        <Modal
          open={!!confirmDelete}
          onClose={() => setConfirmDelete(null)}
          title="テンプレート削除"
          actions={
            <>
              <button className="btn btn-secondary" onClick={() => setConfirmDelete(null)}>キャンセル</button>
              <button className="btn btn-danger" onClick={() => deleteTemplate(confirmDelete.id)}>削除する</button>
            </>
          }
        >
          <p>「{confirmDelete?.name}」を削除しますか？</p>
        </Modal>
      </div>
    );
  }

  window.TemplatesView = { TemplatesView };
})();
