import React, { useState } from "react";

function parseMobProto(txt) {
  const lines = txt.split("\n").filter(Boolean);
  const header = lines[0].split("\t");
  const mobs = lines.slice(1).map(line => {
    const values = line.split("\t");
    const obj = {};
    header.forEach((key, i) => obj[key] = values[i] || "");
    return obj;
  });
  return { header, mobs };
}

export default function MobProtoEditor() {
  const [file, setFile] = useState(null);
  const [data, setData] = useState(null);

  function handleFile(e) {
    const reader = new FileReader();
    reader.onload = () => {
      setData(parseMobProto(reader.result));
    };
    reader.readAsText(e.target.files[0]);
  }

  function handleChange(idx, key, val) {
    setData(prev => {
      const newMobs = prev.mobs.map((mob, i) =>
        i === idx ? { ...mob, [key]: val } : mob
      );
      return { ...prev, mobs: newMobs };
    });
  }

  function handleSave() {
    const txt = [
      data.header.join("\t"),
      ...data.mobs.map(mob =>
        data.header.map(key => mob[key]).join("\t"))
    ].join("\n");
    const blob = new Blob([txt], { type: "text/plain" });
    const url = URL.createObjectURL(blob);
    // download link
    const a = document.createElement("a");
    a.href = url;
    a.download = "mob_proto.txt";
    a.click();
  }

  return (
    <div>
      <input type="file" accept=".txt" onChange={handleFile} /><br />
      {data &&
        <div>
          <table border="1">
            <thead>
              <tr>{data.header