/* Replace the current diagram's PUML source from a pasted string or uploaded file.
   The replacement goes through the same handleSourceChange path as normal edits,
   so it picks up debounced cloud save and exits preview mode if active. */
{
  const { useEffect, useRef, useState } = React;

  function ImportDialog({ open, onCancel, onImport }) {
    const [text, setText] = useState("");
    const [fileName, setFileName] = useState("");
    const textareaRef = useRef(null);
    const fileRef = useRef(null);

    useEffect(() => {
      if (open) {
        setText("");
        setFileName("");
        setTimeout(() => textareaRef.current?.focus(), 0);
      }
    }, [open]);

    if (!open) return null;

    function handleFile(e) {
      const file = e.target.files?.[0];
      if (!file) return;
      const reader = new FileReader();
      reader.onload = () => {
        setText(String(reader.result || ""));
        setFileName(file.name);
      };
      reader.readAsText(file);
    }

    function handleSubmit() {
      const src = text.trim();
      if (!src) return;
      onImport(src);
    }

    const canSubmit = text.trim().length > 0;
    const sizeKb = text ? Math.max(1, Math.round(text.length / 1024)) : 0;
    const oversize = text.length >= 500000;

    return (
      <div className="modal-backdrop" onClick={onCancel}>
        <div className="modal import-dialog" onClick={(e) => e.stopPropagation()}>
          <div className="modal-head">
            <Icon.upload />
            <h3>Replace diagram source</h3>
            <button className="close iconbtn" onClick={onCancel}><Icon.close /></button>
          </div>
          <div className="modal-body">
            <p className="import-hint">
              Paste a PUML definition or upload a <code>.puml</code> file. The current
              diagram's contents will be replaced — version history is preserved.
            </p>
            <textarea
              ref={textareaRef}
              value={text}
              onChange={(e) => setText(e.target.value)}
              placeholder={"@startuml\nclass Foo {\n  - bar : Baz\n}\nFoo --> Baz\n@enduml"}
              spellCheck={false}
            />
            <div className="import-actions">
              <input
                ref={fileRef}
                type="file"
                accept=".puml,.plantuml,.txt,text/plain"
                style={{ display: "none" }}
                onChange={handleFile}
              />
              <button className="btn" onClick={() => fileRef.current?.click()}>
                <Icon.upload /> Upload file
              </button>
              {fileName && <span className="hint">{fileName}</span>}
              {text && (
                <span className={`hint ${oversize ? "error" : ""}`} style={{ marginLeft: "auto" }}>
                  {sizeKb} KB{oversize ? " — exceeds 500 KB limit" : ""}
                </span>
              )}
            </div>
          </div>
          <div className="modal-foot">
            <span className="hint">Replaces current contents. This action goes through autosave.</span>
            <button className="btn" onClick={onCancel}>Cancel</button>
            <button
              className="btn primary"
              onClick={handleSubmit}
              disabled={!canSubmit || oversize}
            >
              <Icon.upload /> Replace
            </button>
          </div>
        </div>
      </div>
    );
  }

  window.ImportDialog = ImportDialog;
}
