<script lang="ts">
  import Dataframe from "@gradio/dataframe";

  let value = {
    data: [
      ["Alice", 25, true, "2023-01-15", "## Marketing Lead\nResponsible for all marketing campaigns and strategies."],
      ["Bob", 30, false, "2022-11-03", "### Product Manager\nLeading the product development team."],
      ["Charlie", 35, true, "2019-05-21", "**CTO**\nOverseeing all technical aspects of the company."],
      ["Diana", 28, false, "2023-03-10", "**HR Manager**\nManaging recruitment and employee relations."],
      ["Evan", 42, true, "2018-09-15", "### Finance Director\nResponsible for financial planning and analysis."],
      ["Fiona", 31, false, "2021-07-22", "## Design Lead\nLeading the UI/UX design team."],
      ["George", 29, true, "2022-04-18", "**Developer**\nWorking on the backend systems."],
      ["Hannah", 36, false, "2020-10-05", "### Sales Manager\nLeading the sales team and strategy."],
      ["Ian", 27, true, "2023-02-28", "## Support Lead\nManaging customer support operations."],
      ["Jane", 33, false, "2019-12-12", "**Operations Manager**\nOverseeing daily business operations."]
    ],
    headers: ["Name", "Age", "Active", "Join Date", "Role"],
  };

  let datatype = ["str", "number", "bool", "date", "markdown"];

  let events = {
    change: [] as string[],
    select: [] as string[],
    input: [] as string[]
  };

  const maxEvents = 5;

  function handle_change(e: CustomEvent) {
    const eventData = `Data changed: ${e.detail.data.length} rows`;
    addEvent('change', eventData);
    console.log("changed", e.detail);
  }

  function handle_select(e: CustomEvent) {
    const eventData = `Selected rows: ${e.detail.index.join(', ')}`;
    addEvent('select', eventData);
    console.log("selected", e.detail);
  }

  function handle_input(e: CustomEvent) {
    const eventData = `Search: "${e.detail}"`;
    addEvent('input', eventData);
    console.log("input", e.detail);
  }

  function addEvent(type: keyof typeof events, message: string) {
    events[type] = [message, ...events[type]].slice(0, maxEvents);
  }

  function addRow() {
    const newRow = [
      `New Person ${Math.floor(Math.random() * 1000)}`,
      Math.floor(Math.random() * 50) + 20,
      Math.random() > 0.5,
      new Date().toISOString().split('T')[0],
      "**New Role**\nJoining the team!"
    ];
    value = {
      data: [...value.data, newRow],
      headers: value.headers
    };
  }

  function clearData() {
    value = {
      data: [],
      headers: value.headers
    };
  }

  function resetData() {
    value = {
      data: [
        ["Alice", 25, true, "2023-01-15", "## Marketing Lead\nResponsible for all marketing campaigns and strategies."],
        ["Bob", 30, false, "2022-11-03", "### Product Manager\nLeading the product development team."],
        ["Charlie", 35, true, "2019-05-21", "**CTO**\nOverseeing all technical aspects of the company."],
        ["Diana", 28, false, "2023-03-10", "**HR Manager**\nManaging recruitment and employee relations."],
        ["Evan", 42, true, "2018-09-15", "### Finance Director\nResponsible for financial planning and analysis."],
        ["Fiona", 31, false, "2021-07-22", "## Design Lead\nLeading the UI/UX design team."],
        ["George", 29, true, "2022-04-18", "**Developer**\nWorking on the backend systems."],
        ["Hannah", 36, false, "2020-10-05", "### Sales Manager\nLeading the sales team and strategy."],
        ["Ian", 27, true, "2023-02-28", "## Support Lead\nManaging customer support operations."],
        ["Jane", 33, false, "2019-12-12", "**Operations Manager**\nOverseeing daily business operations."]
      ],
      headers: ["Name", "Age", "Active", "Join Date", "Role"],
    };
  }
</script>

<div class="container">
  <header>
    <h1>@gradio/dataframe Demo</h1>
    <p class="description">
      Interactive data table with column freezing, search, filtering, and customizable styling. 
      Edit cells, copy data to clipboard, or view in fullscreen mode.
    </p>
  </header>

  <div class="controls">
    <button on:click={addRow}>Add Random Row</button>
    <button on:click={clearData}>Clear Data</button>
    <button on:click={resetData}>Reset Data</button>
  </div>

  <Dataframe
    bind:value
    {datatype}
    show_search="search"
    show_row_numbers={true}
    show_copy_button={true}
    show_fullscreen_button={true}
    editable={true}
    on:change={handle_change}
    on:select={handle_select}
    on:input={handle_input}
    label="Employee Data"
    max_height={500}
    max_chars={100}
    line_breaks={true}
    wrap={false}
  />

  <div class="event-log">
    <h3>Event Log</h3>
    
    {#each Object.entries(events) as [type, messages]}
      <div>
        <h4>{type.charAt(0).toUpperCase() + type.slice(1)} Events:</h4>
        {#if messages.length}
          {#each messages as message}
            <p>{message}</p>
          {/each}
        {:else}
          <p style="color: #9ca3af;">No {type} events yet</p>
        {/if}
      </div>
    {/each}
  </div>
</div>